2

Possible Duplicate:
Is there any sizeof-like method in Java?

I want to determine the size of my class at runtime. In C i do this:

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


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

How i can do this in Java ?

Community
  • 1
  • 1
Vijay Bhaskar Semwal
  • 1,525
  • 3
  • 12
  • 8

4 Answers4

1

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.

zneak
  • 134,922
  • 42
  • 253
  • 328
  • ya i want to know how to calculate – Vijay Bhaskar Semwal Aug 31 '10 at 05:19
  • That way of phrasing it sounds odd to me. It makes it sound like they're just being mean! :-) I'd say: the JVM design says JVM implementers are allowed to perform optimizations which are enabled by not needing to expose the 'size' of objects (or even have it constant per-object, or over time). – Ken Aug 31 '10 at 05:56
1

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.

Mark Peters
  • 80,126
  • 17
  • 159
  • 190
  • `boolean` in HotSpot VM is actually 8 bytes but otherwise this is all good :) – Esko Aug 31 '10 at 05:09
  • @Esko `boolean` is eight __bytes__? – zneak Aug 31 '10 at 05:22
  • ...bits! Damn you, edit time expiration and morning slowness. – Esko Aug 31 '10 at 06:25
  • @Esko: Yes, it looks like you're right that booleans can now be packed into a byte. But after some testing it looks like it's more complicated than that due to word-alignment, etc. Bytes, shorts and chars are similar, they can be packed into sub-word locations. – Mark Peters Aug 31 '10 at 14:30
0

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.

Michael Rutherfurd
  • 13,815
  • 5
  • 29
  • 40
0

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

fastcodejava
  • 39,895
  • 28
  • 133
  • 186