In this post, we will see how to get name of current method being executed in Java.
1. Class.getEnclosingMethod()
The idea is to call Class.getEnclosingMethod()
that returns a java.lang.reflect.Method object that has almost every bit of information on immediately enclosing method of the underlying class. But this come with a significant overhead as it involves creating a new anonymous inner class behind the scenes.
1 2 3 4 5 6 7 8 9 10 |
// Get name of current method being executed in Java public static void fun() { String methodName = new Object() {} .getClass() .getEnclosingMethod() .getName(); System.out.println("Current Method is " + methodName); } |
We can also define inner class within a method to get Class reference as shown below:
1 2 3 4 5 6 7 8 9 10 |
// Get name of current method being executed in Java public static void fun() { class Dummy {}; String methodName = Dummy.class .getEnclosingMethod() .getName(); System.out.println("Current Method is " + methodName); } |
2. Using Throwable Stack Trace – Throwable.getStackTrace()
We know that the Throwable class is the superclass of all errors and exceptions in the Java. We can get an array of stack trace elements representing the stack trace pertaining to a throwable by calling getStackTrace()
on a Throwable instance. The first element of the array represents the top of the stack, which is the last method invocation in the sequence.
1 2 3 4 5 6 7 8 9 |
// Get name of current method being executed in Java public static void fun() { String methodName = new Throwable() .getStackTrace()[0] .getMethodName(); System.out.println("Current Method is " + methodName); } |
We can also use Exception class which extends Throwable.
1 2 3 4 5 6 7 8 9 |
// Get name of current method being executed in Java public static void fun() { String methodName = new Exception() .getStackTrace()[0] .getMethodName(); System.out.println("Current Method is " + methodName); } |
3. Using Thread Stack Trace – Thread.getStackTrace()
We can also use the stack trace of a current thread which returns an array of stack trace elements representing the stack dump of this thread. The second element of the returned array of stack trace contains stack frame of current method.
1 2 3 4 5 6 7 8 9 |
// Get name of current method being executed in Java public static void fun() { String methodName = Thread.currentThread() .getStackTrace()[1] .getMethodName(); System.out.println("Current Method is " + methodName); } |
The problem with using Throwable stack trace and Thread stack trace is that some virtual machines may skip one or more stack frames from the stack trace under some special circumstances.
Thanks for reading.
Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
Leave a Reply