I have to get size of object which type I does not know. It's a template where I want to achieve sth like this:
void sth(T data)
{
System.out.println("Data size = ", sizeof(data));
}
How I can do this in Java?
开发者_开发技巧sizeof - like a C sizeof ;)
It is not an easy task. You have to use java's Instrumentation
.
Here is an example.
Finally I've used this piece of code:
private int getSize(Object data) {
int size = 0;
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(bout);
stream.writeObject(data);
stream.close();
size = bout.size();
} catch (IOException e) {
System.err.println("error: " + e.getMessage());
}
return size;
}
精彩评论