Java:如何获取调用者函数名称 [英] Java: How to get the caller function name
本文介绍了Java:如何获取调用者函数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
要修复测试用例,我需要确定是否从特定的调用函数调用该函数。我无法承受添加布尔参数,因为它会破坏定义的接口。如何解决这个问题?
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?
这就是我想要实现的目标。这里我不能改变operation()的参数,因为它是一个接口实现。
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
...
}
推荐答案
你可以尝试
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[2];//maybe this number needs to be corrected
String methodName = e.getMethodName();
这篇关于Java:如何获取调用者函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文