java:在编译时动态地将代码添加到代码中

时间:2014-12-24 11:15:46

标签: java log4j java-compiler-api

编译后的类文件知道哪条代码在原始java文件中的哪个行号上。我想使用这个功能。

public class A{                                     //1
                                                    //2
    int line; // maybe some modifiers if required   //3
                                                    //4
    public void method1(){                          //5
        System.out.println(line);                   //6
    }                                               //7
                                                    //8
    public void method2(){                          //9
        System.out.println(line);                   //10
    }

}

在编译时,我希望6成为method110成为method2,就像它对最终变量一样。因此,当我运行代码时,我得到了输出

6
10

如果我向上或向下移动一些代码,编译器将处理它,我不必担心这一点。 我需要这个用于记录目的。 Log4j能够为我提供相同的输出,但它从线程堆栈跟踪获取行号,并且它们的文档中提到的效率不高。 %L: Used to output the line number from where the logging request was issued. WARNING Generating caller location information is extremely slow and should be avoided unless execution speed is not an issue.。我相信这项工作会更有效率。

程序员是否可以使用此功能并在编译时在代码中插入行号?我知道它对编译器来说是可能的,但它是否为其他人公开了一个公共api?

1 个答案:

答案 0 :(得分:0)

您希望在运行时获取行号,而不是编译时间。

您可以检查堆栈跟踪。

Thread.getAllStackTraces();

将给出一个每个正在运行的线程的堆栈跟踪的映射。

只需查看它,看看它是什么样的:

    Map<Thread, StackTraceElement[]> allStackTraces = Thread.getAllStackTraces();
    for (StackTraceElement[] elements: allStackTraces.values()) {
        for (StackTraceElement e: elements) {
            System.out.println(e.getClassName() + " " + e.getLineNumber());
        }

    }

因此,如果您知道要检查的线程和对象。当然,你可以得到行号。