This is what I'd like to achieve: if there is a method a()
which calls method b()
, I'd like to know who called method b()
.
public void a(){
b();//but it is not necessarily in the same class
}
public void b(){
String method = getCallerMethod();//returns 'a'
}
Now, this can be achieved efficiently in Java 9+ using the StackWalker
API. In Java 8, I can use Thread.currentThread().getStackTrace()
or new Exception().getStackTrace()
, but both these methods are really slow. I do not need the whole stacktrace, I just need the previous frame in the stacktrace, and only I need the method's name in that frame (and possibly the class name).
Is there a way to achieve this efficiently in Java 8?