1 /* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 import java.lang.reflect.Field; 18 import jdk.internal.misc.Unsafe; 19 20 public class Main { assertLongEquals(long expected, long result)21 private static void assertLongEquals(long expected, long result) { 22 if (expected != result) { 23 throw new Error("Expected: " + expected + ", found: " + result); 24 } 25 } 26 getUnsafe()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 main(String[] args)34 public static void main(String[] args) throws Exception { 35 Unsafe unsafe = getUnsafe(); 36 37 testUnsafeGetLong(unsafe); 38 } 39 testUnsafeGetLong(Unsafe unsafe)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 } 52