0

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

Does Java have operator something like sizeof() in C?

Community
  • 1
  • 1

1 Answers1

0

The answer is no.

However there are some simple approaches to achieve that. Write your own sizeof method.

public static int sizeof(Class cl)
{
    if (cl == Integer.class || cl == int.class) return 4;
    if (cl == Character.class || cl == char.class) return 2;
    //...
}

The size of the object will depend on the JVM implementation. There is the Java SizeOf project which handles all cases correctly.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
  • 1
    There are _many_ classes, not just those encapsulating primitive data types. – John Dvorak Dec 28 '12 at 14:59
  • Actually, you can get the size fairly accurately, see https://github.com/jbellis/jamm, "MemoryMeter is as accurate as java.lang.instrument.Instrumentation.getObjectSize" – sbridges Dec 28 '12 at 15:06