【发布时间】:2014-12-24 11:15:46
【问题描述】:
已编译的类文件知道哪段代码在原始 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 for method1 和 10 for method2 就像它对 final 变量所做的那样。所以当我运行代码时,我得到了输出
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 吗?
【问题讨论】:
-
好吧,你可以尝试实现这一点,...检查 javassist,这个东西可以操纵字节码(没有编译器)。但是你到底想记录什么,所以行号是必需的?我很确定,有更优雅的方式来实现,无论你要实现什么......
标签: java log4j java-compiler-api