Last active
December 10, 2015 13:08
-
-
Save bnyeggen/4438946 to your computer and use it in GitHub Desktop.
Unsafe-based sizeof
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
// A simpler method than reflection-based traversal, using Unsafe | |
public static Unsafe getUnsafe() { | |
Field f = Unsafe.class.getDeclaredField("theUnsafe"); | |
f.setAccessible(true); | |
return (Unsafe) f.get(null); | |
} | |
public static long sizeOf(Object o) { | |
Unsafe u = getUnsafe(); | |
HashSet<Field> fields = new HashSet<Field>(); | |
Class c = o.getClass(); | |
while (c != Object.class) { | |
for (Field f : c.getDeclaredFields()) { | |
if ((f.getModifiers() & Modifier.STATIC) == 0) { | |
fields.add(f); | |
} | |
} | |
c = c.getSuperclass(); | |
} | |
// get offset | |
long maxSize = 0; | |
for (Field f : fields) { | |
long offset = u.objectFieldOffset(f); | |
if (offset > maxSize) { | |
maxSize = offset; | |
} | |
} | |
return ((maxSize/8) + 1) * 8; // padding | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment