If you’re working with Spring, check out "REST With Spring":

>> CHECK OUT THE COURSE

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() {}
      .getClass()
      .getEnclosingMethod()
      .getName();
       
    assertEquals("givenObject_whenGetEnclosingMethod_thenFindMethod",
      methodName);
}

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();
 
    assertEquals(
      "givenThrowable_whenGetStacktrace_thenFindMethod",
      stackTrace[0].getMethodName());
}

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()
      .getStackTrace();
 
    assertEquals(
      "givenCurrentThread_whenGetStackTrace_thenFindMethod",
      stackTrace[1].getMethodName()); 
}

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.



The new Certification Class of "REST With Spring" is finally out:

>> CHECK OUT THE COURSE

Sort by:   newest | oldest | most voted
Antoine Gary BARDET
Guest

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
Guest

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 (site:www.baeldung.com) – so you can simply search on Google.

Hope that helps.
Cheers,
Eugen.

Jakub Gmur
Guest

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

Grzegorz Piwowarek
Guest

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

wpDiscuz