Search code examples
javareflection

Java : Getting the currently executing Method corresponding object


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?


Solution

  • 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.