1 /* 2 * Copyright (c) 2016, 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 package java.util; 25 26 import static java.lang.StackWalker.Option.*; 27 import java.lang.StackWalker.StackFrame; 28 import java.util.stream.Collectors; 29 30 import jdk.internal.reflect.CallerSensitive; 31 import jdk.internal.reflect.Reflection; 32 33 public class CSM { 34 private static StackWalker walker = 35 StackWalker.getInstance(EnumSet.of(RETAIN_CLASS_REFERENCE, 36 SHOW_HIDDEN_FRAMES, 37 SHOW_REFLECT_FRAMES)); 38 39 public static class Result { 40 public final List<Class<?>> callers; 41 public final List<StackWalker.StackFrame> frames; 42 Result(List<Class<?>> callers, 43 List<StackFrame> frames) { 44 this.callers = callers; 45 this.frames = frames; 46 } 47 } 48 49 /** 50 * Returns the caller of this caller-sensitive method returned by 51 * by Reflection::getCallerClass. 52 * 53 * StackWalker::getCallerClass is expected to throw UOE 54 */ 55 @CallerSensitive 56 public static Class<?> caller() { 57 Class<?> c1 = Reflection.getCallerClass(); 58 59 try { 60 Class<?> c2 = walker.getCallerClass(); 61 throw new RuntimeException("Exception not thrown by StackWalker::getCallerClass"); 62 } catch (UnsupportedOperationException e) {} 63 return c1; 64 } 65 66 /** 67 * Returns the caller of this non-caller-sensitive method. 68 */ 69 public static Result getCallerClass() { 70 Class<?> caller = walker.getCallerClass(); 71 return new Result(List.of(caller), dump()); 72 } 73 74 static List<StackFrame> dump() { 75 return walker.walk(s -> s.collect(Collectors.toList())); 76 } 77 }