views:

109

answers:

2

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
   ...       

}
+6  A: 

You could try

StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
String methodName = e.getMethodName();
thejh
new Throwable().fillInStackTrace().getStackTrace()[1].getMethodName()
mootinator
@mootinator: I think that getStackTrace() is faster.
thejh
@thejh - if correctly implemented, they are both the same: `thread.getStackTrace()` does `return (new Exception()).getStackTrace();` if the `thread` is the current one.
Stephen C
@mootinator - the `fillInStackTrace()` call is redundant.
Stephen C
A: 

You could find the calling method using the Stacktrace

Damo