maven 依赖:
<dependency> <groupId>org.openjdk.jol</groupId> <artifactId>jol-core</artifactId> <version>0.9</version> </dependency>
函数使用:
import org.openjdk.jol.info.ClassLayout; public class LayoutDemo { public static void main(String[] args) { MyTest myTest = new MyTest(); System.out.println("myTest:"+myTest); System.out.println(ClassLayout.parseInstance(myTest).toPrintable()); } }
输出内容:
myTest:MyTest(a=0, b=false) # WARNING: Unable to attach Serviceability Agent. You can try again with escalated privileges. Two options: a) use -Djol.tryWithSudo=true to try with sudo; b) echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope com.pilaf.classlayout.MyTest 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) 43 c1 00 f8 (01000011 11000001 00000000 11111000) (-134168253) 12 4 int MyTest.a 0 16 1 boolean MyTest.b false 17 7 (loss due to the next object alignment) Instance size: 24 bytes Space losses: 0 bytes internal + 7 bytes external = 7 bytes total
https://blog.csdn.net/weixin_40865973/article/details/105390202