在Java中,一个方法可以使用反射找出自己的名称吗

在Java中,一个方法可以使用反射找出自己的名称吗,java,reflection,methods,Java,Reflection,Methods,我知道您可以使用Java中的反射在运行时获取类、方法、字段等的名称。 我想知道一个方法在它自己的内部时,是否能找出它自己的名字?另外,我也不想将方法的名称作为字符串参数传递 比如说 public void HelloMyNameIs() { String thisMethodNameIS = //Do something, so the variable equals the method name HelloMyNameIs. } 如果这是可能的话,我想这可能会涉及到使用反射,但可能不

我知道您可以使用Java中的反射在运行时获取类、方法、字段等的名称。 我想知道一个方法在它自己的内部时,是否能找出它自己的名字?另外,我也不想将方法的名称作为字符串参数传递

比如说

public void HelloMyNameIs() {
  String thisMethodNameIS = //Do something, so the variable equals the method name HelloMyNameIs. 
}
如果这是可能的话,我想这可能会涉及到使用反射,但可能不会

如果有人知道,将不胜感激。

使用:

public String getCurrentMethodName()
{
     StackTraceElement stackTraceElements[] = (new Throwable()).getStackTrace();
     return stackTraceElements[1].toString();
}
在要获取其名称的方法内部

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

(不是反射,但我认为这是不可能的。)

使用代理,所有方法(覆盖接口中定义的方法)都可以知道自己的名称

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 ( ) ;
      }
}

这一行程序使用反射:

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

缺点是无法将代码移动到单独的方法。

来自当前线程的堆栈跟踪也:

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

不使用反射,不,在这里回答:此技术会影响性能,因此请谨慎使用。但这是你能得到的最好的解决办法。@柯克·沃尔:非常正确。正因为如此,它真的不应该在发布版本中使用,只用于调试目的。为什么不使用Thread.currentThread().getStackTrace()而不是new Throwable?但是只有其中一个创建了一个额外的Throwable对象可以避免额外的对象创建,仅此而已