有这个方法
public void foo(){
//..
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在运行时获取methodName(在本例中为foo)?
我知道如何获得classname
this.getClass().的getName()
或者通过Method[] methods = this.getClass().getMethods();
方法名称获取所有公共方法
一旦参数也很重要,因为可能有多个具有相同名称的方法
反思是一种方式.另一种缓慢且可能不可靠的方法是使用堆栈跟踪.
StackTraceElement[] trace = new Exception().getStackTrace();
String name = trace[0].getMethodName();
Run Code Online (Sandbox Code Playgroud)
同样的想法,但从线程:
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
String name = trace[0].getMethodName();
Run Code Online (Sandbox Code Playgroud)
我不确定为什么你需要这样做,但你总是可以创建一个new Throwable()and getStackTace()然后查询StackTraceElement.getMethodName().
作为奖励,您可以将整个堆栈跟踪提升到执行点,而不仅仅是立即封闭的方法.
我使用如下代码:
/**
* Proper use of this class is
* String testName = (new Util.MethodNameHelper(){}).getName();
* or
* Method me = (new Util.MethodNameHelper(){}).getMethod();
* the anonymous class allows easy access to the method name of the enclosing scope.
*/
public static class MethodNameHelper {
public String getName() {
final Method myMethod = this.getClass().getEnclosingMethod();
if (null == myMethod) {
// This happens when we are non-anonymously instantiated
return this.getClass().getSimpleName() + ".unknown()"; // return a less useful string
}
final String className = myMethod.getDeclaringClass().getSimpleName();
return className + "." + myMethod.getName() + "()";
}
public Method getMethod() {
return this.getClass().getEnclosingMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
只需去掉 className + "." 部分,看看它是否满足您的需求。