java中查看变量占用内存

java中查看变量占用内存

摘要

java中查看变量占用内存

编译java文件

javac ObjectSizeFetcher.java 得到 ObjectSizeFetcher.class

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

打包进jar

jar cvf ObjectSizeFetcherAgent.jar ObjectSizeFetcher.class

把MANIFEST.MF放进ObjectSizeFetcherAgent.jar

MANIFEST.MF的内容如下

 Premain-Class: ObjectSizeFetcher

编写测试类C.java

 public class C {
    private int x;
    private int y;

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

javac C.java 得到C.class

测试效果

 java -javaagent:ObjectSizeFetcherAgent.jar C