1 /* 2 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 /* 25 * @test 26 * @bug 8137058 27 * @summary Basic test for the unsupported Reflection.getCallerClass(int) 28 * @modules jdk.unsupported 29 */ 30 31 import sun.reflect.Reflection; 32 33 public class GetCallerClassWithDepth { 34 public static void main(String[] args) throws Exception { 35 Class<?> c = Test.test(); 36 assertEquals(c, GetCallerClassWithDepth.class); 37 Class<?> caller = Test.caller(); 38 assertEquals(caller, GetCallerClassWithDepth.class); 39 Test.selfTest(); 40 41 try { 42 Reflection.getCallerClass(-1); 43 throw new RuntimeException("getCallerClass(-1) should fail"); 44 } catch (Error e) { 45 System.out.println("Expected: " + e.getMessage()); 46 } 47 } 48 49 public Class<?> getCallerClass() { 50 // 0: Reflection 1: getCallerClass 2: Test.test 3: main 51 return Reflection.getCallerClass(3); 52 } 53 54 static void assertEquals(Class<?> c, Class<?> expected) { 55 if (c != expected) { 56 throw new RuntimeException("Incorrect caller: " + c); 57 } 58 } 59 60 static class Test { 61 // Returns the caller of this method 62 public static Class<?> test() { 63 return new GetCallerClassWithDepth().getCallerClass(); 64 } 65 66 // Returns the caller of this method 67 public static Class<?> caller() { 68 // 0: Reflection 1: Test.caller 2: main 69 return Reflection.getCallerClass(2); 70 } 71 public static void selfTest() { 72 // 0: Reflection 1: Test.selfTest 73 Class<?> c = Reflection.getCallerClass(1); 74 assertEquals(c, Test.class); 75 Inner1.deep(); 76 } 77 78 static class Inner1 { 79 static void deep() { 80 deeper(); 81 } 82 static void deeper() { 83 Inner2.deepest(); 84 } 85 static class Inner2 { 86 static void deepest() { 87 // 0: Reflection 1: deepest 2: deeper 3: deep 4: Test.selfTest 88 Class<?> c = Reflection.getCallerClass(4); 89 assertEquals(c, Test.class); 90 } 91 } 92 } 93 } 94 }