| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
import java.lang.reflect.Field; |
| 18 |
import jdk.internal.misc.Unsafe; |
| 19 |
|
| 20 |
public class Main { |
| 21 |
private static void assertLongEquals(long expected, long result) { |
| 22 |
if (expected != result) { |
| 23 |
throw new Error("Expected: " + expected + ", found: " + result); |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
private static Unsafe getUnsafe() throws Exception { |
| 28 |
Class<?> unsafeClass = Class.forName("jdk.internal.misc.Unsafe"); |
| 29 |
Field f = unsafeClass.getDeclaredField("theUnsafe"); |
| 30 |
f.setAccessible(true); |
| 31 |
return (Unsafe) f.get(null); |
| 32 |
} |
| 33 |
|
| 34 |
public static void main(String[] args) throws Exception { |
| 35 |
Unsafe unsafe = getUnsafe(); |
| 36 |
|
| 37 |
testUnsafeGetLong(unsafe); |
| 38 |
} |
| 39 |
|
| 40 |
public static void testUnsafeGetLong(Unsafe unsafe) throws Exception { |
| 41 |
TestClass test = new TestClass(); |
| 42 |
Field longField = TestClass.class.getDeclaredField("longVar"); |
| 43 |
long lvar = unsafe.objectFieldOffset(longField); |
| 44 |
lvar = unsafe.getLong(test, lvar); |
| 45 |
assertLongEquals(1122334455667788L, lvar); |
| 46 |
} |
| 47 |
|
| 48 |
private static class TestClass { |
| 49 |
public long longVar = 1122334455667788L; |
| 50 |
} |
| 51 |
} |