你可以使用java.lang.instrument包
编译该类并将其放在JAR中:
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
使用getObjectSize:
public class C { private int x; private int y; public static void main(String [] args) { System.out.println(ObjectSizeFetcher.getObjectSize(new C())); }}调用:
java -javaagent:ObjectSizeFetcherAgent.jar C



