0

I have been struggling for finding the exact size of java objects. I have tried different options and non of them are working correctly. Then I tried to serialize the object and find the size of the serialized object. The size of the serialized object is very small, like in few kilo byte. So I doubted my method. I was wondering is it the correct way? Is there any problem you people see in this procedure? Please help...

user3212493
  • 165
  • 2
  • 11

1 Answers1

1

You can convert your object into a byte array using ObjectOutputStream and ByteArrayOutputStream:

public static int sizeof(Object obj) throws IOException {

    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOutputStream);

    objectOutputStream.writeObject(obj);
    objectOutputStream.flush();
    objectOutputStream.close();

    return byteOutputStream.toByteArray().length;
}
Parth Soni
  • 11,158
  • 4
  • 32
  • 54
aurelius
  • 3,946
  • 7
  • 40
  • 73