Skip to content

Instantly share code, notes, and snippets.

@AndrewChanChina
Created May 27, 2015 03:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewChanChina/95888ae52fc2f560b4ec to your computer and use it in GitHub Desktop.
Save AndrewChanChina/95888ae52fc2f560b4ec to your computer and use it in GitHub Desktop.
class Memory {
/**
* Function that get the size of an object.
*
* @param object
* @return Size in bytes of the object or -1 if the object
* is null.
* @throws IOException
*/
public static final int sizeOf(Object object) throws IOException {
if (object == null)
return -1;
// Special output stream use to write the content
// of an output stream to an internal byte array.
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream();
// Output stream that can write object
ObjectOutputStream objectOutputStream =
new ObjectOutputStream(byteArrayOutputStream);
// Write object and close the output stream
objectOutputStream.writeObject(object);
objectOutputStream.flush();
objectOutputStream.close();
// Get the byte array
byte[] byteArray = byteArrayOutputStream.toByteArray();
// TODO can the toByteArray() method return a
// null array ?
return byteArray == null ? 0 : byteArray.length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment