java 动态获取当前方法名称的更短方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13609509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:23:57  来源:igfitidea点击:

Shorter method for getting the name of the current method dynamically

java

提问by davidahines

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(

回答by NPE

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

怎么样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.

由于这使您能够检查堆栈跟踪的更高级别,因此您可以轻松地将其包装在辅助方法中(见下文)。它还为您提供了获取更多信息的选项,而不仅仅是方法名称,例如文件名、行号等。

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

编辑辅助方法可能看起来像这样(感谢@Esailija):

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

回答by dreamcrash

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.

我不知道分拣机的方式来做到这一点。

回答by AlexR

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)

您可以使用thread.currentThread().getStacktrace()[0].getMethodName(). 但这甚至需要比new Throwable().getStacktrace()(参见http://alexradzin.blogspot.co.il/2011/12/how-slow-getstacktrace-is.html)更多的时间