Java动态获取当前行号| Java Debug 笔记

本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看 活动链接

原问题地址:stackoverflow.com/questions/1…

Q:

Java 中是否可以通过反射或一些很棒的 API 动态获取当前行号?就像发生异常时一样,行号会像这样在堆栈跟踪中打印出来:

at weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:348)
复制代码

现在有一种方法可以像下面的代码那样进行打印或记录吗?

log.error("Error in: " + this.getClass.getName() + "at line #"+ this.getClass.getActualLine());
复制代码

您可能会问,为什么我不简单地打印行号?好吧,因为在调用特定的 log.error() 方法之前,代码可能会被删除或添加。

A:

我能够使用 Thread.currentThread().getStackTrace() 方法创建一组函数,这些函数可以共同产生称为第一个方法的代码的行号,如下所示:

/** @return The line number of the code that ran this method
 * @author Brian_Entei */
public static int getLineNumber() {
    return ___8drrd3148796d_Xaf();
}

/** This methods name is ridiculous on purpose to prevent any other method
 * names in the stack trace from potentially matching this one.
 * 
 * @return The line number of the code that called the method that called
 *         this method(Should only be called by getLineNumber()).
 * @author Brian_Entei */
private static int ___8drrd3148796d_Xaf() {
    boolean thisOne = false;
    int thisOneCountDown = 1;
    StackTraceElement[] elements = Thread.currentThread().getStackTrace();
    for(StackTraceElement element : elements) {
        String methodName = element.getMethodName();
        int lineNum = element.getLineNumber();
        if(thisOne && (thisOneCountDown == 0)) {
            return lineNum;
        } else if(thisOne) {
            thisOneCountDown--;
        }
        if(methodName.equals("___8drrd3148796d_Xaf")) {
            thisOne = true;
        }
    }
    return -1;
}
复制代码

希望这可以帮助!我将它们放在实用程序类中,以便它们不受干扰,但仍易于访问。第二个方法是私有的,以防止第一个方法以外的任何其他方法调用它,以使其始终正常工作。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享