Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to get the caller function name

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.

operation() {    if not called from performancetest() method        do expensive bookkeeping operation    ...         } 
like image 877
softwarematter Avatar asked Oct 31 '10 22:10

softwarematter


People also ask

How do you find the current method name?

The current method name that contains the execution point that is represented by the current stack trace element is provided by the java. lang. StackTraceElement. getMethodName() method.

How do you call a name in Java?

To call a method in Java, simply write the method's name followed by two parentheses () and a semicolon(;). If the method has parameters in the declaration, those parameters are passed within the parentheses () but this time without their datatypes specified.

What is the caller of a function?

A Function object's caller property returns the function that invoked the specified function. For strict, async function, and generator function callers, accessing the caller property throws an exception.


2 Answers

You could try

StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); StackTraceElement e = stacktrace[2];//maybe this number needs to be corrected String methodName = e.getMethodName(); 
like image 193
thejh Avatar answered Sep 20 '22 17:09

thejh


Here's a function I wrote to Log the function name of the function that calls it. It runs up the stack trace until it finds a function named logIt, then displays the next name. It's a dirty hack, so don't do it unless you're using it to debug.

private static void logIt() {     StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();     boolean logged = false;     boolean foundMe = false;     for(int i=0; i<stacktrace.length; i++) {         StackTraceElement e = stacktrace[i];         String methodName = e.getMethodName();         if (foundMe) {             if (!methodName.startsWith("access$")) {                 Log.i(TAG, String.format(Locale.US, "%s.%s", e.getClassName(), methodName));                 logged = true;                 break;             }         } else {             if (methodName.equals("logIt")) {                 foundMe = true;             }         }     }     if (!logged)         Log.e(TAG, "unlogged call"); } 
like image 37
JohnnyLambada Avatar answered Sep 18 '22 17:09

JohnnyLambada