javareflectionjol

Jol to find the offset of fields in the class


I use jol to find the offset of the fields as below:

import java.lang.reflect.Field;

public static void main(String[] args) throws NoSuchFieldException {
    System.out.println(ClassLayout.parseClass(Field.class).toPrintable());
}

The output:

OFF  SZ   TYPE DESCRIPTION               VALUE
  0   8        (object header: mark)     N/A
  8   4        (object header: class)    N/A
 12   4        (object alignment gap)    
Instance size: 16 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total

The 3rd row shows (object alignment gap) but didn't show the offset of the fields such as override, name, type and such on.

How can I get those field's offset? Or is there other ways to get the offset?


Solution

  • The JOL IntelliJ Plugin shows the offset information, apparently.

    Install the plugin, use Field somewhere in your code, put the cursor on the text Field, then go to Code -> Show Object Layout

    enter image description here

    Note that there is also a selector for the JVM implementation to use.

    Interestingly, using sudo with the JOL command line tool report a different size for a Field object - 72 bytes for my JVM.

    $ sudo java -jar jol-cli-latest.jar internals java.lang.reflect.Field
    

    Output excerpt:

    java.lang.reflect.Field object internals:
    OFF  SZ   TYPE DESCRIPTION               VALUE
      0   8        (object header: mark)     0x0000000000000005 (biasable; age: 0)
      8   4        (object header: class)    0x0006e918
     12   4        (object alignment gap)    
    Instance size: 72 bytes
    Space losses: 0 bytes internal + 4 bytes external = 4 bytes total