7

I know that you can use reflection in Java to get the name of class, methods, fields...etc at run time. I was wondering can a method figure out its own name while its inside it's self? Also, I don't want to pass the name of the method as a String parameter either.

For example

public void HelloMyNameIs() {
  String thisMethodNameIS = //Do something, so the variable equals the method name HelloMyNameIs. 
}

If it that is possible, I was thinking it would probably involve using reflection, but maybe it doesn't.

If anybody know, it would be greatly appreciated.

Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
grebwerd
  • 81
  • 1
  • 8
  • Not with reflection, no, answer here: http://stackoverflow.com/questions/442747/getting-the-name-of-the-current-executing-method-java – Affe Aug 02 '11 at 23:19

4 Answers4

9

Use:

public String getCurrentMethodName()
{
     StackTraceElement stackTraceElements[] = (new Throwable()).getStackTrace();
     return stackTraceElements[1].toString();
}

inside the method you want to get the name of.

public void HelloMyNameIs()
{
    String thisMethodNameIS = getCurrentMethodName();
}

(Not reflection, but I don't think it is possible.)

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
6

This one-liner works using reflection:

public void HelloMyNameIs() {
  String thisMethodNameIS = new Object(){}.getClass().getEnclosingMethod().getName();
}

The downside is that the code can't be moved to a separate method.

Andrejs
  • 26,885
  • 12
  • 107
  • 96
3

Using a Proxy all your methods (that override a method defined in an interface) can know their own names.

import java . lang . reflect . * ;

interface MyInterface
{
      void myfun ( ) ;
}

class MyClass implements MyInterface
{
      public void myfun ( ) { /* implementation */ }
}

class Main
{
      public static void main ( String [ ] args )
      {
            MyInterface m1 = new MyClass ( ) ;
            MyInterface m2 = ( MyInterface ) ( Proxy . newProxyInstance (
                  MyInterface . class() . getClassLoader ( ) ,
                  { MyInterface . class } ,
                  new InvocationHandler ( )
                  {
                        public Object invokeMethod ( Object proxy , Method method , Object [ ] args ) throws Throwable
                        {
                             System . out . println ( "Hello.  I am the method " + method . getName ( ) ) ;
                             method . invoke ( m1 , args ) ;
                        }
                  }
            ) ) ;
            m2 . fun ( ) ;
      }
}
emory
  • 10,725
  • 2
  • 30
  • 58
0

Stack trace from current thread also:

public void aMethod() {  
    System.out.println(Thread.currentThread().getStackTrace()[0].getMethodName()); 
}