Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:


1. Overview

Sometimes we need to know the name of the current Java method being executed.

This quick article presents a couple of simple ways of getting hold of the method name in the current execution stack.

2. Using getEnclosingMethod

We can find the name of the method being executed by using the getEnclosingMethod() API:

public void givenObject_whenGetEnclosingMethod_thenFindMethod() {
    String methodName = new Object() {}

3. Using Throwable Stack Trace

Using a Throwable stack trace gives us stack trace with the method currently being executed:

public void givenThrowable_whenGetStacktrace_thenFindMethod() {
    StackTraceElement[] stackTrace = new Throwable().getStackTrace();

4. Using Thread Stack Trace

Also, the stack trace of a current thread (since JDK 1.5) usually includes the name of the method that is being executed:

public void givenCurrentThread_whenGetStackTrace_thenFindMethod() {
    StackTraceElement[] stackTrace = Thread.currentThread()

However, we need to remember that this solution has one significant drawback. Some virtual machines may skip one or more stack frames. Although this is not common, we should be aware that this can happen.

5. Conclusion

In this tutorial, we have presented some examples how to get the name of the currently executed method. Examples are based on stack traces and the getEnclosingMethod().

As always, you can check out the examples provided in this article over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:


newest oldest most voted
Notify of
Antoine Gary BARDET
Antoine Gary BARDET

It may not be the right place to discuss that but have you ever thought about adding a “Search” functionality in your website? There are so many great articles, we should be able to find them using key words.

Eugen Paraschiv

Hey @antoinegarybardet:disqus ,
Yeah, I’ve considered that in the past – and I may revisit the decision in the future, but for now, I wanted to keep the interface simple and so there’s no search.

That being said, keep in mind that Google allows you to restrict your search to a single domain ( – so you can simply search on Google.

Hope that helps.

Jakub Gmur

Which of these is used in Spring (for example to name beans in JavaConfig)?

Grzegorz Piwowarek
Grzegorz Piwowarek

Probably none of them. This is a slightly different use case, for the method discovery Reflection seems more suitable