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 8025799 27 * @summary sun.reflect.Reflection.getCallerClass(int) 28 * @modules java.base/sun.reflect 29 * @run main GetCallerClassWithDepth 30 */ 31 32 public class GetCallerClassWithDepth { 33 public static void main(String[] args) throws Exception { 34 Class<?> c = Test.test(); 35 assertEquals(c, GetCallerClassWithDepth.class); 36 Class<?> caller = Test.caller(); 37 assertEquals(caller, GetCallerClassWithDepth.class); 38 Test.selfTest(); 39 40 try { 41 sun.reflect.Reflection.getCallerClass(-1); 42 throw new RuntimeException("getCallerClass(-1) should fail"); 43 } catch (Error e) { 44 System.out.println("Expected: " + e.getMessage()); 45 } 46 } 47 48 public Class<?> getCallerClass() { 49 // 0: Reflection 1: getCallerClass 2: Test.test 3: main 50 return sun.reflect.Reflection.getCallerClass(3); 51 } 52 53 static void assertEquals(Class<?> c, Class<?> expected) { 54 if (c != expected) { 55 throw new RuntimeException("Incorrect caller: " + c); 56 } 57 } 58 59 static class Test { 60 // Returns the caller of this method 61 public static Class<?> test() { 62 return new GetCallerClassWithDepth().getCallerClass(); 63 } 64 65 // Returns the caller of this method 66 public static Class<?> caller() { 67 // 0: Reflection 1: Test.caller 2: main 68 return sun.reflect.Reflection.getCallerClass(2); 69 } 70 public static void selfTest() { 71 // 0: Reflection 1: Test.selfTest 72 Class<?> c = sun.reflect.Reflection.getCallerClass(1); 73 assertEquals(c, Test.class); 74 Inner1.deep(); 75 } 76 77 static class Inner1 { 78 static void deep() { 79 deeper(); 80 } 81 static void deeper() { 82 Inner2.deepest(); 83 } 84 static class Inner2 { 85 static void deepest() { 86 // 0: Reflection 1: deepest 2: deeper 3: deep 4: Test.selfTest 87 Class<?> c = sun.reflect.Reflection.getCallerClass(4); 88 assertEquals(c, Test.class); 89 } 90 } 91 } 92 } 93 }