使用Instrumentation类:Java提供了Instrumentation类,可以通过该类的getObjectSize()方法来获取对象的大小。可以通过以下步骤来实现:
package sizeof;
import java.lang.instrument.Instrumentation;
public class ObjectShallowSize {
private static Instrumentation inst;
public static void premain(String agentArgs, Instrumentation instP){
inst = instP;
}
public static long sizeOf(Object obj){
if (inst == null) {
throw new IllegalStateException("Instrumentation not initialized");
}
return inst.getObjectSize(obj);
}
}
定义META-INF/MANIFEST.MF文件
Premain-Class: sizeof.ObjectShallowSize
cd 编译后的类和META-INF文件夹所在目录
jar cvfm java-agent-sizeof.jar META-INF/MANIFEST.MF
项目打成jar 包,给需要使用ObjectShallowSize的工程引入该jar包,并通过代码测试对象所占内存大小
在测试项目工程引入jar 包
<dependency>
<!-- 模块原有groupId -->
<groupId>org.example</groupId>
<!-- 模块原有artifactId -->
<artifactId>ObjectShallowSize</artifactId>
<!-- 模块原有version -->
<version>1.0-SNAPSHOT</version>
<!-- 系统依赖范围,往往与本机绑定,不过我本次和项目中的jar包进行了绑定 -->
<scope>system</scope>
<!-- 本地jar包绝对路径,lib是我们新建的目录, -->
<systemPath>E:/project/AgentTest/lib/ObjectShallowSize-1.0-SNAPSHOT.jar</systemPath>
</dependency>
编写测试类
import sizeof.ObjectShallowSize;
import java.io.IOException;
public class SizeofWithInstrumetation {
public static void main(String[] args) throws IOException {
Object obj=new Object(){}.getClass().getEnclosingClass();
System.out.println(ObjectShallowSize.sizeOf(obj));
}
}
运行配置jvm-options 添加
-javaagent:E:/project/AgentTest/lib/java-agent-sizeof.jar