打印对象的内存布局
/**
* 打印对象信息
*/
@Test
public void printObj() {
User user = new User();
System.out.println("hashCode:"+user.hashCode());
System.out.println(ClassLayout.parseInstance(user).toPrintable());
}
private static class User{
}
com.txp.owner.basic.record.test202302.TestMain20230208$User object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 4 (object header) 01 3a 99 d6 (00000001 00111010 10011001 11010110) (-694601215)
4 4 (object header) 1e 00 00 00 (00011110 00000000 00000000 00000000) (30)
8 4 (object header) 07 26 01 f8 (00000111 00100110 00000001 11111000) (-134142457)
12 4 (loss due to the next object alignment)
Instance size: 16 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
对象头一定是8的倍数,前8个字节存储的是mark world信息,后面8个字节存储的是类型指针。
因为开启了指针压缩,第2个8个字节实际只占用了4个字节。
对象=对象头+实例数据+padding填充字节组成。
对象头=mark world(8个字节)+类型指针(8个字节)
参考:
https://mp.weixin.qq.com/s/pF0ursDX6-LD1h5LSSAttw