如何取的Java源代码文件中文件名和行号:)
在C/C++的程序,编译器提供了两个宏来支持取得源文件中的行号和文件名,这两个宏是__FILE__,__LINE__
你可以如下的方法打印行号和文件名
1
2
3
4
5
6
|
#include <stdio.h>
int
main()
{
fprintf
(stdout,
"[%s:%d] Hello World!"
,__FILE__,__LINE__);
return
0;
}
|
但是在JAVA下没有这两个宏,那么我们如何来取得文件名和行号,翻阅JDK,我们找到StackTraceElement这个类。这个类可以从Throwable取得,另外也可以从Thread类取得,通过这些我写如下的一个打印行号的测试程序:
1
2
3
4
5
6
7
8
9
10
11
12
|
public
class
LineNo {
public
static
int
getLineNumber() {
return
Thread.currentThread().getStackTrace()[
2
].getLineNumber();
}
public
static
String getFileName() {
return
Thread.currentThread().getStackTrace()[
2
].getFileName();
}
public
static
void
main(String args[]) {
System.out.println(
"["
+getFileName()+
":"
+ getLineNumber()+
"]"
+
"Hello World!"
);
}
}
|
留下一个问题,上面程序中的magic数字 2 代表什么含义呢?