[Q#4065518][A#4065546] Java: How to get the caller function name
https://stackoverflow.com/q/4065518
To fix a test case I need to identify whether the function is called from a particular caller function. I can't afford to add a boolean parameter because it would break the interfaces defined. How to go about this? This is what I want to achieve. Here I can't change the parameters of operation() as it is an interface implementation.
Answer
https://stackoverflow.com/a/4065546
You could try
APIzation
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
String methodName = e.getMethodName();
package com.stackoverflow.api;
public class Human4065546 {
public static String getMethodNameFromStackTrace(int num) {
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[num];
return e.getMethodName();
}
}
package com.stackoverflow.api;
/**
* Java: How to get the caller function name
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/4065546">https://stackoverflow.com/a/4065546</a>
*/
public class APIzator4065546 {
public static String java() throws Exception {
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
// maybe this number needs to be corrected
StackTraceElement e = stacktrace[2];
return e.getMethodName();
}
}