在 HotSpot JVM 中,每個對象在堆內存中由四個部分組成:
boolean/byte 1B,char/short 2B,int/float 4B,long/double 8B。| 類定義 | 佔用字節數 | 說明 |
|---|---|---|
class Empty {} | 8 | 僅對象頭 8B |
class OneBool { boolean b; } | 16 | 對象頭 8B + boolean 1B + 填充 7B |
class EightBools { boolean b1...b8; } | 16 | 對象頭 8B + 8×boolean 8B = 16B,恰好對齊 |
class Mixed { int i; Object ref; } | 24 | 對象頭 8B + int 4B + ref 4B = 16B,填充 8B 對齊到 24B |
-XX:+UseCompressedOops,引用仍為 4B;關閉後變為 8B。可使用 jol-core (Java Object Layout) 工具在運行時精確測量對象大小:
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>0.16</version>
</dependency>
// 使用示例
System.out.println(ClassLayout.parseClass(MyClass.class).toPrintable());