Reputation: 1683
having the method
public void foo(){
//..
}
Is there a way to get the methodName (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
Upvotes: 12
Views: 11300
Reputation: 119
Use this code:
System.out.println(new Throwable().getStackTrace()[0].getMethodName());
Upvotes: 2
Reputation: 86
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.
Upvotes: 0
Reputation: 1161
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.
Upvotes: 5
Reputation: 10891
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" ;
...
}
}
Upvotes: 1
Reputation: 12543
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();
Upvotes: 5
Reputation: 383966
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.
Upvotes: 5