开发者

Sizeof unknown type object

开发者 https://www.devze.com 2023-01-22 12:54 出处:网络
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:

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

精彩评论

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