Created
May 27, 2015 03:07
-
-
Save AndrewChanChina/95888ae52fc2f560b4ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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