Java:如何获取调用者函数名称

dev*_*ull 23 java unit-testing

为了修复测试用例,我需要确定是否从特定的调用函数调用该函数.我无法承受添加布尔参数,因为它会破坏定义的接口.怎么去这个?

这就是我想要实现的目标.这里我不能改变operation()的参数,因为它是一个接口实现.

operation()
{
   if not called from performancetest() method
       do expensive bookkeeping operation
   ...       

}
Run Code Online (Sandbox Code Playgroud)

the*_*ejh 66

你可以试试

StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
String methodName = e.getMethodName();
Run Code Online (Sandbox Code Playgroud)

  • new Throwable().fillInStackTrace().getStackTrace()[1] .getMethodName() (2认同)

Nat*_*han 16

这里的代码更现代(在 Java 9+ 中可用)并且性能更好。

private static String getCallerMethodName()
{
   return StackWalker.
      getInstance().
      walk(stream -> stream.skip(1).findFirst().get()).
      getMethodName();
}
Run Code Online (Sandbox Code Playgroud)

根据需要更改skip(1)为更大的数字,以提高堆栈的位置。

Thread.currentThread().getStackTrace()这比它不遍历整个堆栈并分配所有堆栈帧的性能更好。它只在堆栈上遍历两个帧。

该方法可以适用于返回StackWalker.StackFrame具有有关该方法的大量信息。