This post will discuss how to get the name of the current method being executed in Java.

1. Using Class.getEnclosingMethod() method

The idea is to call the Class.getEnclosingMethod() that returns a java.lang.reflect.Method object with almost every bit of information on the immediately enclosing method of the underlying class. This comes with a significant overhead as it involves creating a new anonymous inner class behind the scenes.

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

2. Using Throwable Stack Trace – Throwable.getStackTrace() method

We know that the Throwable class is the superclass of all errors and exceptions in 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 the Exception class, which extends Throwable.

3. Using Thread Stack Trace – Thread.getStackTrace() method

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 the stack frame of the 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.

That’s all about getting the name of the current method being executed in Java.