三国纷争
您可以使用jol来获取该类的布局。(但是要小心,您可能需要更深入地了解其背后的机制,不要盲目相信结果,并且要知道这只是当前使用的VM的估算值(在我的案例中为1.7.0_76 x64 win):):我使用CLI版本,我猜正确的方法是将库包含在您的项目中,但是无论如何,它似乎可以这样工作:test>java -cp target\classes;jol-cli-0.3.1-full.jar org.openjdk.jol.Main internals test.CheckStoreRunning 64-bit HotSpot VM.Using compressed oop with 0-bit shift.Using compressed klass with 0-bit shift.Objects are 8 bytes aligned.Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]VM fails to invoke the default constructor, falling back to class-only introspection.test.CheckStore object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 12 (object header) N/A 12 1 boolean CheckStore.state N/A 13 3 (alignment/padding gap) N/A 16 4 String CheckStore.displayText N/A 20 4 String CheckStore.meaningfulText N/A 24 4 URL CheckStore.url N/A 28 4 (loss due to the next object alignment)Instance size: 32 bytes (estimated, the sample instance is not available)Space losses: 3 bytes internal + 4 bytes external = 7 bytes total与自动压缩的oops相同:test>java -XX:-UseCompressedOops -cp target\classes;jol-cli-0.3.1-full.jar org.openjdk.jol.Main internals test.CheckStoreRunning 64-bit HotSpot VM.Objects are 8 bytes aligned.Field sizes by type: 8, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]Array element sizes: 8, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]VM fails to invoke the default constructor, falling back to class-only introspection.test.CheckStore object internals: OFFSET SIZE TYPE DESCRIPTION VALUE 0 16 (object header) N/A 16 1 boolean CheckStore.state N/A 17 7 (alignment/padding gap) N/A 24 8 String CheckStore.displayText N/A 32 8 String CheckStore.meaningfulText N/A 40 8 URL CheckStore.url N/AInstance size: 48 bytes (estimated, the sample instance is not available)Space losses: 7 bytes internal + 0 bytes external = 7 bytes total如果您的字段为null,那么这些只是对象本身的布局,那么它将不会指向更多对象,否则您还必须查看目标类型(URL和String)。(并且,如果您拥有所有这些实例的多个实例,则取决于您使用相同的多次还是不同的实例)。空字段不能在内存中跳过,因为分配实例时需要调整实例的大小。所以这些字段都是预先构造的,它们只是不引用堆上其他地方分配的对象。注意:如果实现默认的构造函数,则会获得更多详细信息,但是在这种情况下的大小将是相同的。如果您想知道字段的顺序和填充的来源,可以查看这篇文章 -(基本上,它将对象对齐8个字节,按大小对字段进行排序,将相同类型分组在一起,最后引用。来自超级类型的字段排在最前面, 4个字节对齐。)