I was wondering if there is a way to know the method name being executed at run time?
For instance, inside a private void doSomething (String s)
method, I'd like to know that I am executing the doSomething (String s)
method.
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.
Yes you can. It is called recursion .
Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur.
Two or more methods can have the same name inside the same class if they accept different arguments. This feature is known as method overloading.
Since JDK1.5, you don't need an Exception to get the StackTrace,
you can get it with Thread.currentThread().getStackTrace()
:
public class Test2 { public static void main(String args[]) { new Test2().doit(); } public void doit() { System.out.println( Thread.currentThread().getStackTrace()[1].getMethodName()); // output : doit } }
System.out.println(new Exception().getStackTrace()[0].getMethodName());
Also See
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