Last active
December 21, 2015 11:29
-
-
Save kaushiks/6299350 to your computer and use it in GitHub Desktop.
Java (Hotspot) class layout printer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sun.misc.Unsafe; | |
import java.lang.reflect.*; | |
import java.util.*; | |
class FieldLayoutPrinter { | |
private static Unsafe _unsafe = null; | |
static { | |
try { | |
Field field = Unsafe.class.getDeclaredField("theUnsafe"); | |
field.setAccessible(true); | |
_unsafe = (Unsafe)field.get(null); | |
} catch (Exception e) { | |
System.out.println("ERROR: Couldn't reflect on sun.misc.Unsafe."); | |
} | |
} | |
static List<Field> get_field_list(final Class klass) | |
{ | |
List<Field> fields = null; | |
if (!klass.isPrimitive()) { | |
fields = new ArrayList<Field>(); | |
Class current = klass; | |
while (current != null) { | |
Collections.addAll(fields, current.getDeclaredFields()); | |
current = (current == Object.class) ? null: current.getSuperclass(); | |
} | |
} | |
return fields; | |
} | |
static void print_field_list(final Object o) | |
{ | |
for (final Field field: get_field_list(o.getClass())) { | |
if ((field.getModifiers() & Modifier.STATIC) != 0) continue; | |
System.out.println(_unsafe.objectFieldOffset(field) + | |
" " + | |
field.getDeclaringClass().getName() + | |
"::" + | |
field.getName()); | |
} | |
} | |
public static void main(String[] args) | |
{ | |
print_field_list("Hello, World!"); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment