You can use the java.lang.instrument
package.
Compile and put this class in a 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);
}
}
Add the following to your MANIFEST.MF
:
Premain-Class: ObjectSizeFetcher
Use the getObjectSize()
method:
public class C {
private int x;
private int y;
public static void main(String [] args) {
System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
}
}
Invoke with:
java -javaagent:ObjectSizeFetcherAgent.jar C
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…