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 sun.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("sun.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 System.loadLibrary(args[0]); 36 Unsafe unsafe = getUnsafe(); 37 38 testUnsafeGetLong(unsafe); 39 } 40 testUnsafeGetLong(Unsafe unsafe)41 public static void testUnsafeGetLong(Unsafe unsafe) throws Exception { 42 TestClass test = new TestClass(); 43 Field longField = TestClass.class.getDeclaredField("longVar"); 44 long lvar = unsafe.objectFieldOffset(longField); 45 lvar = unsafe.getLong(test, lvar); 46 assertLongEquals(1122334455667788L, lvar); 47 } 48 49 private static class TestClass { 50 public long longVar = 1122334455667788L; 51 } 52 } 53