Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter method for getting the name of the current method dynamically [duplicate]

Tags:

java

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(
like image 263
davidahines Avatar asked Nov 28 '12 16:11

davidahines


People also ask

What is the use of GET method in Java?

The get method returns the value of the variable name . The set method takes a parameter ( newName ) and assigns it to the name variable. The this keyword is used to refer to the current object.

How do you find the current method name?

The current method name that contains the execution point that is represented by the current stack trace element is provided by the java. lang. StackTraceElement. getMethodName() method.


2 Answers

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();
} 
like image 58
NPE Avatar answered Oct 09 '22 09:10

NPE


You can also use

Thread.currentThread().getStackTrace()[1].getMethodName() 

contains the last method call, but is not shorter that

new Object() {}.getClass().getEnclosingMethod().getName

I am not aware of a sorter way to do it.

like image 20
dreamcrash Avatar answered Oct 09 '22 10:10

dreamcrash