Get name of current method being executed in Java

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.

We can also define inner class within a method to get Class reference as shown below:


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.

We can also use Exception class which extends Throwable.


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.

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

Notify of