The following prints the current caller class. Note that in this case, the [StackWalker](<http://download.java.net/java/jdk9/docs/api/java/lang/StackWalker.html>)
needs to be created with the option [RETAIN_CLASS_REFERENCE](<http://download.java.net/java/jdk9/docs/api/java/lang/StackWalker.Option.html#RETAIN_CLASS_REFERENCE>)
, so that Class
instances are retained in the [StackFrame](<http://download.java.net/java/jdk9/docs/api/java/lang/StackWalker.StackFrame.html>)
objects. Otherwise an exception would occur.
public class StackWalkerExample {
public static void main(String[] args) {
FooHelper.foo();
}
}
class FooHelper {
protected static void foo() {
BarHelper.bar();
}
}
class BarHelper {
protected static void bar() {
System.out.println(StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE).getCallerClass());
}
}
Output:
class test.FooHelper