Java : Getting the currently executing Method corr

2020-06-12 03:46发布

问题:

What is the most elegant way to get the currently executing method as a Method object ?

My first obvious way to do it would be to use a static method in a helper class, which would load the current thread stack, get the right stack trace element, and construct the Method element from its information.

Is there a more elegant way to achieve this?

回答1:

Out of the box, I'm not aware of a better way to do this.

One thing to consider perhaps would be aspects - you could weave an aspect into the code that fired around all method invocations and pushed the current Method object to a ThreadLocal (based on the reflective information available from the joinpoint).

This would be probably prohibitively expensive if it really fired on all methods, but depending on what you're doing with the results, you may be able to constrain the capturing down to certain packages/classes, which would help. You may be able to defer the actual lookup of the Method too until such time as it's used, and instead store the name of the method and arguments etc.

I have my doubts whether there's going to be a particularly cheap way to achieve this, though.



回答2:

This topic is covered in deeper depth in this SO Question.

I need to do the same thing and I found the best solution to be the one provided by @alexsmail.

It seems a little bit hacky but the general idea is that you declare a local class in the method and then take advantage of class.getEnclosingMethod();

Code slightly modified from @alexsmail's solution:

public class SomeClass {
   public void foo(){
      class Local {};
      Method m = Local.class.getEnclosingMethod();
   }
 }