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






你可能感兴趣的:(java:获取一个对象占用内存的大小)