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 ... }
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.
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.
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.
You could try
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace(); StackTraceElement e = stacktrace[2];//maybe this number needs to be corrected String methodName = e.getMethodName();
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"); }
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