开发者

Sizeof unknown type object

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;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜