views:

66

answers:

3

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

+2  A: 

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();
Jonathon
why is it unreliable? do you have an example for getting it via reflection?
Martin Dürrmeier
@Martin Dürrmeier - reflection is more involved. I've added links for information about the `getStackTrace` method and potential unreliability.
Jonathon
@Jonathon thanks for the link. Could you give me a hint how to do it via Reflection?
Martin Dürrmeier
@Martin Dürrmeier - Usually with reflection you know the method name beforehand. Using a `Class` object, you can call `getMethods` and match up the name with the proper argument types to get a `Method` object. Check out the JavaDoc for `Class`: http://java.sun.com/javase/6/docs/api/java/lang/Class.html
Jonathon
+2  A: 

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

polygenelubricants
Thanks! I'm creating CommonBaseEvents need apart from the className the MethodName see also http://download.boulder.ibm.com/ibmdl/pub/software/dw/library/autonomic/books/cbepractice/index.htm#_Toc130892562
Martin Dürrmeier
Jonathon pointed out what the JavaDoc of 'getStackTace()' says "Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace." So i'm trying reflection. Do you have an idea how it works via Reflection?
Martin Dürrmeier
A: 

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" ;
          ...
     }
}
emory