您可以使用jol 来获取该类的布局。 (但要小心,您可能需要对其背后的机制有更深入的了解,不要盲目相信结果,并注意这只是对当前使用的 VM 的估计(在我的情况下为 1.7.0_76 x64 获胜:):
我使用 CLI 版本,我想正确的方法是将库包含在您的项目中,但无论如何,它似乎是这样工作的:
test>java -cp target\classes;jol-cli-0.3.1-full.jar org.openjdk.jol.Main internals test.CheckStore
Running 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.CheckStore
Running 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/A
Instance size: 48 bytes (estimated, the sample instance is not available)
Space losses: 7 bytes internal + 0 bytes external = 7 bytes total
如果您的字段为空,这些只是对象本身的布局,那么它将不会指向更多对象,否则您还必须查看目标类型(URL 和String)。 (如果您有所有实例的多个实例,则取决于您是多次使用相同的实例还是不同的实例)。不能在内存中跳过空字段,因为它需要在分配实例时调整其大小。所以这些字段都是预先构建的,它们只是不引用堆上其他地方的分配对象。
注意:如果您实现默认构造函数,您将获得更多详细信息,但在这种特定情况下的大小将是相同的。如果您想知道字段的序列和填充来自哪里,您可以检查this article - (基本上它在 8 个字节上对齐对象,按大小对字段进行排序,将相同类型组合在一起,最后引用。来自超类型的字段是第一个, 4 字节对齐。)