java:获取一个对象占用内存的大小

In Java, what is the best way to determine the size of an object?中给出了一个很好的答案。

首先,将下面的类编译并放入jar中:

import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}




在MANIFEST.MF中添加如下内容:
Premain-Class: ObjectSizeFetcher



然后,我们就可以在main函数中尝试获取对象占用的内存大小了:
public class C {
    private int x;
    private int y;

    public static void main(String [] args) {
        System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
    }
}



将上面的代码打包成jar后,执行:
java -javaagent:ObjectSizeFetcherAgent.jar C



通过 -javaagent参数和MANIFEST.MF中的内容,在执行 类C中的main函数之前,ObjectSizeFetcher中的premain方法会执行。这样,instrumentation就有了应用的Instrumentation类型的对象。


更多:
Calculate size of Object in Java: http://stackoverflow.com/questions/9368764/calculate-size-of-object-in-java

In Java, what is the best way to determine the size of an object?: http://stackoverflow.com/questions/52353/in-java-what-is-the-best-way-to-determine-the-size-of-an-object

JavaAgent: http://www.cnblogs.com/diyunpeng/archive/2011/05/26/2057932.html

jamm: https://github.com/jbellis/jamm






转载于:https://my.oschina.net/letiantian/blog/372893

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值