你可以使用该
java.lang.instrumentation软件包:
http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html
它具有一种方法,可用于获取特定于实现的对象大小的近似值以及与对象相关的开销。
Sergey链接的答案有一个很好的例子,我将在这里重新发布,但是你应该已经从他的评论中进行了研究:
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); }}使用getObjectSize:
public class C { private int x; private int y; public static void main(String [] args) { System.out.println(ObjectSizeFetcher.getObjectSize(new C())); }}


