Shorter method for getting the name of the current

2020-05-27 03:21发布

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(

标签: java
3条回答
做个烂人
2楼-- · 2020-05-27 04:05

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.

查看更多
叛逆
3楼-- · 2020-05-27 04:18

You can use thread.currentThread().getStacktrace()[0].getMethodName(). But this even takes more time than new Throwable().getStacktrace() (see http://alexradzin.blogspot.co.il/2011/12/how-slow-getstacktrace-is.html)

查看更多
够拽才男人
4楼-- · 2020-05-27 04:19

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();
} 
查看更多
登录 后发表回答