Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 564
glmxndr Avatar asked Feb 28 '11 09:02

glmxndr


People also ask

How can I find the method that called the current method in Java?

The current method name that contains the execution point that is represented by the current stack trace element is provided by the java. lang. StackTraceElement. getMethodName() method.

How do you call a method from an object in Java?

Remember that.. The dot ( . ) is used to access the object's attributes and methods. To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( ; ). A class must have a matching filename ( Main and Main.

How do you get a method name?

Method Class | getName() Method in Java Method class is helpful to get the name of methods, as a String. To get name of all methods of a class, get all the methods of that class object. Then call getName() on those method objects. Return Value: It returns the name of the method, as String.


1 Answers

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();
   }
 }
like image 57
NSjonas Avatar answered Oct 13 '22 11:10

NSjonas