get Name of enclosing Method
having the method
public void foo(){
//..
}
Is there a way to get the meth开发者_JAVA技巧odName (in this case foo) at runtime?
I know how to get the classname via
this.getClass().getName()
or to get all public methods via
Method[] methods = this.getClass().getMethods();
Once I have the method name the parameters would also be important as there could be several methods with same name
I'm not sure why you need to do this, but you can always create a new Throwable()
and getStackTace()
, then query StackTraceElement.getMethodName()
.
As a bonus, you get the whole stack trace up to the execution point, not just the immediately enclosing method.
Related questions
- Java: Determining Current Call Stack (For Diagnostic Purposes)
- Call trace in java
Reflection is one way. Another slow and potentially unreliable way is with a stack trace.
StackTraceElement[] trace = new Exception().getStackTrace();
String name = trace[0].getMethodName();
Same idea but from the thread:
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
String name = trace[0].getMethodName();
I use code like the following:
/**
* 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();
}
}
Just leave off the className + "." part and see if it meets your needs.
Use this code:
System.out.println(new Throwable().getStackTrace()[0].getMethodName());
You can hard code the name.
// The Annotation Processor will complain if the two method names get out of synch
class MyClass
{
@HardCodedMethodName ( )
void myMethod ( )
{
@ HardCodedMethodName // Untried but it seems you should be able to produce an annotation processor that compile time enforces that myname = the method name.
String myname = "myMethod" ;
...
}
}
This question was asked years ago, but I think it would be worth synthesize the previous answers in a simpler expression:
String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
In spite of its ugliness and the reliability issues cited, it is clean and can be easily used with Log.x()
functions to help in debugging.
精彩评论