【问题标题】:Shorter method for getting the name of the current method dynamically [duplicate]动态获取当前方法名称的更短方法[重复]
【发布时间】:2012-11-16 13:35:04
【问题描述】:

我正在寻找一种无需创建空白对象即可获取当前方法名称的方法。有没有办法做到这一点?这将整理我们的日志记录代码。

这是我们现在要做的:

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

【问题讨论】:

    标签: java


    【解决方案1】:

    Thread.currentThread().getStackTrace()[1]怎么样?

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

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

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

    【讨论】:

    • 高级0表示当前方法,1表示调用方法
    • @dreamcrash:你真的试过了吗?我有。
    • public static String methodName() { return Thread.currentThread().getStackTrace()[2].getMethodName(); } 非常适合我
    • @NPE 对不起,你是对的 0 将返回 getStackTrace。 +1 为不便之处。
    • @dreamcrash 支持您的评论,因为我想知道为什么我们应该使用 [1] 并且懒得检查 [0] 会返回什么 :)
    【解决方案2】:

    你也可以使用

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

    包含最后一个方法调用,但不短于

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

    我不知道有一种分拣机方法。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2011-08-05
        • 2016-03-13
        • 2011-01-04
        • 1970-01-01
        • 2023-03-10
        • 2010-10-01
        • 1970-01-01
        • 2012-03-08
        • 2010-09-19
        相关资源
        最近更新 更多