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?
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.
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.
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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With