Java でオブジェクトのメモリサイズを計算する方法
Javaでは、java.lang.instrument.Instrumentationクラスを使用してオブジェクトのメモリーサイズを計算できます。手順:
- java.lang.instrument.Instrumentation
import java.lang.instrument.Instrumentation;
public class ObjectSizeCalculator implements Instrumentation {
// 实现接口中的方法
}
- オブジェクトのサイズを取得
import java.lang.instrument.Instrumentation;
public class ObjectSizeCalculator implements Instrumentation {
private static Instrumentation instrumentation;
// 实现接口中的方法
public static void premain(String agentArgs, Instrumentation inst) {
instrumentation = inst;
}
public static long getObjectSize(Object obj) {
if (instrumentation == null) {
throw new IllegalStateException("Instrumentation is not initialized");
}
return instrumentation.getObjectSize(obj);
}
}
- オブジェクトサイズを取得する
public class Main {
public static void main(String[] args) {
Object obj = new Object();
long size = ObjectSizeCalculator.getObjectSize(obj);
System.out.println("Object size: " + size + " bytes");
}
}
注意:Instrumentationクラスを使用するには、Javaプログラムを実行時に特別なパラメータ「-javaagent:path/to/your/ObjectSizeCalculator.jar」を追加する必要があります。ただし、「path/to/your/ObjectSizeCalculator.jar」はObjectSizeCalculatorクラスを含むJarファイルのパスです。
さらに、`getObjectSize()` メソッドは直接的なオブジェクト自身のサイズのみを計算できるだけで、オブジェクトの中の参照オブジェクトが占有するメモリサイズは計算できないことに注意。オブジェクトの中の参照オブジェクトのメモリサイズを計算する場合、`getObjectSize()` メソッドを再帰的に使用する。