开发者

How to calculate the size of class in java ..?is any method like sizeof() in c..? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Is there any sizeof-like method in Java?

I want to determine the size of my class at runtime. In 开发者_Go百科C i do this:

struct
{
int id;
char name[30];
} registry


void main()
{
int size = sizeof(registry);
}

How i can do this in Java ?


You can't. The Java virtual machine doesn't want you to know it.

There are probably other ways to do what you really wanted to do with this information.


VMs differ in how they store variables, etc internally. Most modern 32-bit VMs are similar though. You can probably estimate the shallow size of a class instance like this:

sizeInBytes = C + 4 * (fieldCount)

Where C is some constant.

This is because typically all fields are given a word width, which is often still 4 bytes internally to the JVM. The deep size of the class is more difficult to compute, but basically you recursively add the size of each referent object. Arrays are typically 1*arr.length bytes in size for booleans and bytes, 2*arr.length for chars and shorts, 4*arr.length for ints and floats, and 8*arr.length for doubles and longs.

Probably the easiest way to get an estimate at runtime is to measure how Runtime.freeMemory() changes as you instantiate objects of your class. None of this should be used for program logic of course; just for JVM tweaking or curiousity.


Have a look at ClassMexer which is just a simple implementation of the new java.lang.instrument.Instrumentation interface. Just follow the instructions, which are pretty simple.

It may be too intrusive for your use as it runs as javaagent but from your example it should be ok.


You can get an estimate, getting the exact number if difficult. Why is it necessary?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜