潇湘沐
它依赖于体系结构/JDK。对于现代的JDK和64位架构,对象有12字节的头,填充8字节,所以最小对象大小是16字节。您可以使用一个名为Java对象布局若要确定对象的大小和获取任何实体的对象布局和内部结构的详细信息,或通过类引用猜测此信息。Integer在我的环境中的输出示例:Running 64-bit HotSpot VM.Using compressed oop with 3-bit shift.Using compressed klass with 3-bit shift.Objects are 8 bytes aligned
.Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]java.lang.Integer object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE 0 12 (object header)
N/A 12 4 int Integer.value
N/AInstance size: 16 bytes (estimated, the sample instance is not available)Space losses: 0 bytes internal + 0 bytes external = 0 bytes total因此,对于Integer,实例大小为16字节,因为4字节int紧压在标头后面和填充边界之前。代码示例:import org.openjdk.jol.info.ClassLayout;import org.openjdk.jol.util.VMSupport;public static void main(String[] args) {
System.out.println(VMSupport.vmDetails());
System.out.println(ClassLayout.parseClass(Integer.class).toPrintable());}如果你使用Maven,就可以得到Jol:<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>0.3.2</version></dependency>