1、maven 依赖
<dependency>
<groupId>org.openjdk.jol</groupId>
<artifactId>jol-core</artifactId>
<version>0.10</version>
</dependency>
2、测试类
package constxiong;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.info.GraphLayout;
/**
* 测试对象占用的内存信息
*/
public class TestObjectSize {
public static void main(String[] args) {
System.out.println("对象内部信息");
System.out.println(ClassLayout.parseInstance(new String("ConstXiong")).toPrintable());
System.out.println(ClassLayout.parseInstance(new char[]{'C', 'o', 'n', 's', 't', 'X', 'i', 'o', 'n', 'g'}).toPrintable());
System.out.println("对象整体信息");
System.out.println(GraphLayout.parseInstance(new String("ConstXiong")).toPrintable());
System.out.println(GraphLayout.parseInstance(new char[]{'C', 'o', 'n', 's', 't', 'X', 'i', 'o', 'n', 'g'}).toPrintable());
System.out.println("对象占用总空间");
System.out.println(GraphLayout.parseInstance(new String("ConstXiong")).totalSize());
System.out.println(GraphLayout.parseInstance(new char[]{'C', 'o', 'n', 's', 't', 'X', 'i', 'o', 'n', 'g'}).totalSize());
}
}
3、打印结果
对象内部信息
java.lang.String 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) d0 16 3e 17 (11010000 00010110 00111110 00010111) (389945040)
12 4 char[] String.value [C, o, n, s, t, X, i, o, n, g]
16 4 int String.hash 0
20 4 (loss due to the next object alignment)
Instance size: 24 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
[C 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) 08 02 3e 17 (00001000 00000010 00111110 00010111) (389939720)
12 4 (object header) 0a 00 00 00 (00001010 00000000 00000000 00000000) (10)
16 20 char [C.<elements> N/A
36 4 (loss due to the next object alignment)
Instance size: 40 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
对象整体信息
java.lang.String@1a93a7cad object externals:
ADDRESS SIZE TYPE PATH VALUE
d6284f40 40 [C .value [C, o, n, s, t, X, i, o, n, g]
d6284f68 11751072 (something else) (somewhere else) (something else)
d6db9e08 24 java.lang.String (object)
[C@3b764bced object externals:
ADDRESS SIZE TYPE PATH VALUE
d6df9610 40 [C [C, o, n, s, t, X, i, o, n, g]
对象占用总空间
64
40
内存分析:
https://www.javanav.com/val/49e9ce5857744a39a88b1977d84086c7.html