获取封闭方法的名称

时间:2010-06-29 15:19:55

标签: java reflection

有方法

public void foo(){
  //..    
}

有没有办法在运行时获取methodName(在本例中为foo)?

我知道如何通过

获取classname
  

this.getClass()。的getName()

或通过获取所有公共方法 Method[] methods = this.getClass().getMethods(); 一旦我有方法名称,参数也很重要,因为可能有几个同名的方法

6 个答案:

答案 0 :(得分:5)

反思是一种方式。另一种缓慢的potentially unreliable方式是使用堆栈跟踪。

StackTraceElement[] trace = new Exception().getStackTrace();
String name = trace[0].getMethodName();

同样的想法,但来自thread

StackTraceElement[] trace = Thread.currentThread().getStackTrace();
String name = trace[0].getMethodName();

答案 1 :(得分:5)

我不确定您为什么需要这样做,但您始终可以创建new Throwable()getStackTace(),然后查询StackTraceElement.getMethodName()

作为奖励,您可以将整个堆栈跟踪到达执行点,而不仅仅是立即封闭的方法。

相关问题

答案 2 :(得分:4)

我使用如下代码:

  /**
   * Proper use of this class is
   *     String testName = (new Util.MethodNameHelper(){}).getName();
   *  or
   *     Method me = (new Util.MethodNameHelper(){}).getMethod();
   * the anonymous class allows easy access to the method name of the enclosing scope.
   */
  public static class MethodNameHelper {
    public String getName() {
      final Method myMethod = this.getClass().getEnclosingMethod();
      if (null == myMethod) {
        // This happens when we are non-anonymously instantiated
        return this.getClass().getSimpleName() + ".unknown()"; // return a less useful string
      }
      final String className = myMethod.getDeclaringClass().getSimpleName();
      return className + "." + myMethod.getName() + "()";
    }

    public Method getMethod() {
      return this.getClass().getEnclosingMethod();
    }
}

请不要使用className +“。”部分,看看它是否符合您的需求。

答案 3 :(得分:2)

使用此代码:

System.out.println(new Throwable().getStackTrace()[0].getMethodName());

答案 4 :(得分:1)

您可以对名称进行硬编码。

// The Annotation Processor will complain if the two method names get out of synch
class MyClass
{
    @HardCodedMethodName ( ) 
     void myMethod ( )
     {
          @ HardCodedMethodName // Untried but it seems you should be able to produce an annotation processor that compile time enforces that myname = the method name.
          String myname = "myMethod" ;
          ...
     }
}

答案 5 :(得分:0)

这个问题是在几年前被问到的,但我认为值得用更简单的表达方式综合以前的答案:

String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();

尽管它的丑陋和引用的可靠性问题,它很干净,可以很容易地与Log.x()函数一起使用,以帮助调试。