Get name of current method being executed in Java
Getting name of currently executing method is useful for handling exceptions and debugging purposes.
Below are different methods to get currently executing method :
- Using Throwable Stack Trace :
- Using getEnclosingMethod() method
- Using Thread Stack Trace : The Thread.getStackTrace() method returns array of stack trace elements. The second element of the returned array of stack trace contains name of method of current thread.
public class GFG {
public static void foo()
{
String nameofCurrMethod = Thread.currentThread()
.getStackTrace()[ 1 ]
.getMethodName();
System.out.println( "Name of current method: "
+ nameofCurrMethod);
}
public static void main(String[] args)
{
foo();
}
}
|
Output:
Name of current method: foo
Last Updated :
08 Nov, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...