import java.lang.instrument.Instrumentation;public class ObjectSizeFetcher { private static Instrumentation instrumentation; public static void premain(String args, Instrumentation inst) { instrumentation = inst; } public static long getObjectSize(Object o) { return instrumentation.getObjectSize(o); }}
在MANIFEST.MF中添加如下内容:
Premain-Class: ObjectSizeFetcher
然后,我们就可以在main函数中尝试获取对象占用的内存大小了:
public class C { private int x; private int y; public static void main(String [] args) { System.out.println(ObjectSizeFetcher.getObjectSize(new C())); }}
将上面的代码打包成jar后,执行:
java -javaagent:ObjectSizeFetcherAgent.jar C
通过 -javaagent参数和MANIFEST.MF中的内容,在执行 类C中的main函数之前,ObjectSizeFetcher中的premain方法会执行。这样,instrumentation就有了应用的Instrumentation类型的对象。 更多: Calculate size of Object in Java: In Java, what is the best way to determine the size of an object?: JavaAgent: jamm: