The Java9+ technique of getting the call stack uses StackWalker
. The equivalent of Ritesh Puj's answer using StackWalker
is as follows:
public class Main {
public static void main(String[] args) {
example();
}
public static void example() {
B b = new B();
b.methodB();
}
}
class B {
public void methodB(){
System.out.println("I am methodB");
StackWalker.getInstance()
.walk(frames -> frames.skip(1).findFirst())
.ifPresent(frame -> {
System.out.println("I was called by a method named: " + frame.getMethodName());
System.out.println("That method is in class: " + frame.getClassName());
});
}
}
The advantage of using StackWalker
is that it generates stack frames lazily. This avoids the expense that Thread.getStackTrace()
incurs when creating a large array of stack frames. Creating the full stack trace is especially wasteful if the call stack is deep, and if you only want to look up a couple frames, as in this example.