引用当前方法的关键字/方法

时间:2019-06-20 14:59:52

标签: java reflection

是否可以使用Reflection将当前方法作为参数传递? 换句话说,除了方法以外,是否还有类似this的关键字?

例如:

class ReflectionUtils {
  public static void printMethod(Method method){
    System.out.print(method.getName());
  }
}

// then...

class callerClass {
  void callerMethod(){
    ReflectionUtils.printMethod(/* "this" but for methods */)
  }
}

// would print: "callerMethod"

我想将callerMethod从自身传递给printMethod方法。有什么方法可以执行此操作而无需解析堆栈跟踪?

1 个答案:

答案 0 :(得分:1)

据我所知,没有关键字。

我不知道您的确切需求,但是您也可以使用Class#getEnclosingMethod来做到这一点:

Method enclosingMethod = new Object() {}
                              .getClass()
                              .getEnclosingMethod();

这与您提出的方法类似。