Shorter method for getting the name of the current method dynamically

java

Solution

How about `Thread.currentThread().getStackTrace()[1]`?

Since this enables you to examine higher levels of the stack trace, you could easily wrap this in a helper method (see below). It also gives you the option to get quite a bit more info than just the method name, such as the file name, line number etc.

edit The helper method could look something like this (thanks @Esailija):

public static String getMethodName() {
    return Thread.currentThread().getStackTrace()[2].getMethodName();
} 

Problem

I'm looking for a way to get the name of the current method without having to create a blank object. Is there a way to do this? This would tidy up our logging code. Here is what we do now: ``` new Object() {}.getClass().getEnclosingMethod().getName( ```

Original source

Related problems