How to get a method name in Java

There are some cases when you want to know the current name of the method that is executing. The class name is a simple matter to extract via this.getClass().getName(), but the current executing method is harder to get.

The attached file is a Java agent, that has the method "getCurrentMethodName()" in it, which does not take any arguments. This method could (should?) be placed in your library of utility functions, but I have placed it in an agent just to show how it works.

Here is a shorter version supplied by Guillaume Dubé to me:

public String getCurrentMethodName()
StackTraceElement stackTraceElements[] = (new Throwable()).getStackTrace();
return stackTraceElements[1].toString();