Simple Object Size Calculator


The easiest way to calculate the Object Size, be it Integer,String, User data type, Beans et al.

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectSizeCalculator implements Serializable {

private static final long serialVersionUID = 1L;

public static int sizeOf(Object obj) {
ByteArrayOutputStream byteObject = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream;
try {
objectOutputStream = new ObjectOutputStream(byteObject);
objectOutputStream.writeObject(obj);
objectOutputStream.flush();
objectOutputStream.close();
byteObject.close();
} catch (IOException e) {
e.printStackTrace();
}

return byteObject.size();

}

public static void main(String args[]) {
ObjectSizeCalculator obj = new ObjectSizeCalculator();
int size = ObjectSizeCalculator.sizeOf(obj);
System.out.println(“Object size in bytes: ” + size);
}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s