I think that cannot be done directly as in C/C++ .. But u can use the concept of classLoader .
You may summ up the no of bytes they occupy.. and for object references take the size as long variable. U can do this only by this way.. No direct way is available to my knowledge. If u find any other way pls let us know..
Yes you can with 1.5 using http://java.sun.com/j2se/1.5.0/docs/api/java/lang/instrument/Instrumentation.html
It is not straight forward process. You have to create your own agent:
package foocompany.agent;
public class SimpleAgent {
private static Instrumentation instrumentation;
/** Creates a new instance of SimpleAgent */
public SimpleAgent() {
}
public static void premain(String agentArgs, Instrumentation inst) {
instrumentation = inst;
}
public static long sizeOf(Object object) {
return instrumentation.getObjectSize(object);
}
}
Create a manifest file:
Manifest-Version: 1.0
Premain-Class: foocompany.agent.SimpleAgent
Combine them into a jar file.
And then specify the jar file on the command line:
java -javaagent:"<path to jar>\simpleagent.jar" <rest of arguments...>
Then you can call SimpleAgent.sizeOf() on any object from your program.