Can a method determine its own name using reflection in Java

I know that you can use reflection in Java to get the name of the class, methods, fields ... etc. at runtime. I was wondering if a method can determine its name while it is inside itself? In addition, I do not want to pass the method name as a String parameter.

for example

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

If this is possible, I thought it would probably be due to the use of reflection, but perhaps it is not.

If anyone knows, he will be very grateful.

+7
source share
4 answers

Using:

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

inside the method you want to get.

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

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

+9
source

This single-line frame works using reflection:

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

The disadvantage is that the code cannot be ported to a separate method.

+6
source

Using a proxy server, all of your methods (which override the method defined in the 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 ( ) ; } } 
+3
source

The stack trace from the current thread also:

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

All Articles