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
【Java学习资源】整理推荐
- Java 8 Stream API Demo
- Druid 使用
- 借助 libreoffice,word 转 pdf 体验
- Java 动态代理
- openjdk jol 工具打印 Java 对象内存布局
- Spring整合MyBatis
- MyBatis 自定义插件
- MyBatis 延迟加载
- MyBatis 1对1 1对多 关联查询
- MyBatis insert 获取自增主键
- MyBatis 批量插入
- 分页插件 Mybatis-PageHelper
- MyBatis 原生使用
- Sharding-JDBC 实现分库分表
- JDK1.8 中的日期与时间 API
- Sharding-JDBC 实现读写分离
【Java面试题与答案】整理推荐