I have two methods. In one of them, I call second one. In this second one I need to know name of method, which call this (second) one.
Is this even possible?
public class Test {
public void foo() {
String m = getCallingMethodName();
}
public String getCallingMethodName() {
return callerMethodName; //should return "foo"
}
}
With this you can obtain the current method name:
String method_name = Thread.currentThread().getStackTrace()[1].getMethodName());
The other answers here are correct, but I thought I'd add a small note of caution. This won't work if you call things using reflection and also it might not get the right stack frame if you have any AOP joinpoints / proxies etc.
For example...
import java.lang.reflect.Method;
public class CallerInfoFinder {
public static void main(String[] args) throws Exception {
otherMethod(); // Prints "main"
Method m = CallerInfoFinder.class.getDeclaredMethod("otherMethod");
m.invoke(null); // Prints "invoke0"
}
private static void otherMethod() {
System.out.println(new Exception().getStackTrace()[1].getMethodName());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With