Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a method figure out its own name using reflection in Java [duplicate]

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.

like image 644
grebwerd Avatar asked Aug 02 '11 23:08

grebwerd


3 Answers

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.)

like image 133
Evan Mulawski Avatar answered Nov 07 '22 16:11

Evan Mulawski


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.

like image 27
Andrejs Avatar answered Nov 07 '22 17:11

Andrejs


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 ( ) ;
      }
}
like image 41
emory Avatar answered Nov 07 '22 16:11

emory