JoseHdez_2
JoseHdez_2

Reputation: 4171

Keyword/method to reference current method

Is there a way to pass the current method as a parameter using Reflection? In other words, is there something like the this keyword, but for methods?

For example:

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"

I want to pass callerMethod from itself to the printMethod method. Is there any way to do this, without parsing the stack trace?

Upvotes: 0

Views: 52

Answers (1)

Archaos
Archaos

Reputation: 46

As far as I know there is no keyword for that.

I do not know your exact needs, but you could also do this using Class#getEnclosingMethod like that:

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

It is similar to the way you proposed.

Upvotes: 1

Related Questions