How we can get size of Object in Java?

How we can get size of Object in Java?

Bellow code will give you size of Object in java.

public static byte[] sizeOf(Object obj) throws java.io.IOException
{
ByteArrayOutputStream byteObject = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteObject);
objectOutputStream.writeObject(obj);
objectOutputStream.flush();
objectOutputStream.close();
byteObject.close();

return byteObject.toByteArray();
}

7 thoughts on “How we can get size of Object in Java?

  1. Hi,

    If you are looking for size of serialized object, then you can use

    public long getObjectSize(Object objToGetSize)
    {
    try
    {
    long objSize = 0;
    String objectFilePath = System.getProperty(“java.io.tmpdir”) + “/yourTmpDir/”;
    File fileExist = new File(objectFilePath + “\\executionObject.dat”);
    if(fileExist.exists())
    fileExist.delete();

    File mkDir = new File(objectFilePath);
    mkDir.mkdir();

    FileOutputStream foutGroupNodes = new FileOutputStream(objectFilePath + “\\abc.dat”);
    ObjectOutputStream oosGroupNodes = new ObjectOutputStream(foutGroupNodes);
    oosGroupNodes.writeObject(objToGetSize);
    Log.debugLog(className, “getObjectSize”, “”, “”, “Object Serialized”);

    File F1 = new File(objectFilePath + “\\abc.dat”);
    objSize = F1.length();

    return objSize;
    }
    catch(Exception ex)
    {
    return 0;
    }
    }

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