java对象从宏观上来看,简单的由类名,属性,方法组成
在创建(new)对象时,一个对象由对象头,属性值,填充数据组成
做一个测试
1.导入包
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>0.9</version>
</dependency>
2.写一个main方法输出打印
public static void main(String[] args) {
String s = ClassLayout.parseInstance(new L()).toPrintable();
System.out.println(s);
}
public class L{
int a ;
}
3.运行控制输出:
lock.L object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1)
4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
8 4 (object header) 18 0a 94 16 (00011000 00001010 10010100 00010110) (378800664)
12 4 int L.a1 0
Instance size: 16 bytes
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
object header为对象头,一个占用4字节,三个占用12字节,int属性a占用4字节 共16个字节
那么现在把int替换成boolean呢
输出:
lock.L object internals:
OFFSET SIZE TYPE DESCRIPTION VALUE
0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1)
4 4 (object header) 00 00 00 00 (00000000 00000000 00000000 00000000) (0)
8 4 (object header) 18 0a 9a 16 (00011000 00001010 10011010 00010110) (379193880)
12 1 boolean L.flag false
13 3 (loss due to the next object alignment)
Instance size: 16 bytes
Space losses: 0 bytes internal + 3 bytes external = 3 bytes total
一个boolean对象占用1个字节,此时共13字节,然后新增了3字节的填充数据
此时我的操作系统为86bit,那么jvm的规范每个对象大小必须为8的倍数,所以补充了3字节的填充数据用来对齐