【问题标题】:Can a method figure out its own name using reflection in Java [duplicate]方法可以使用Java中的反射找出自己的名称吗?
【发布时间】:2011-10-18 16:34:49
【问题描述】:

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

例如

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

如果可能的话,我想它可能会涉及使用反射,但也许不会。

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

【问题讨论】:

标签: java reflection methods


【解决方案1】:

用途:

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

在你想要获取名字的方法里面。

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

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

【讨论】:

  • 这种技术会影响性能,因此请谨慎使用。但这是您将获得的最佳解决方案。
  • @Kirk Woll:非常正确。因此,它真的不应该在发布版本中使用,仅用于调试目的。
  • 为什么不使用 Thread.currentThread().getStackTrace() 而不是 new Throwable?
  • 但其中只有一个创建了额外的 Throwable 对象
  • 可以避免这种额外的对象创建,仅此而已
【解决方案2】:

这个单行使用反射来工作:

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

缺点是代码不能移动到单独的方法中。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 2010-10-17
        • 1970-01-01
        • 2020-07-05
        • 2012-09-03
        • 1970-01-01
        • 1970-01-01
        • 2012-11-16
        • 1970-01-01
        • 2019-08-13
        相关资源
        最近更新 更多