Welcome 微信登录

首页 / 软件开发 / JAVA / Java如何取源文件中文件名和行号

Java如何取源文件中文件名和行号2011-01-23 coolshell 酷壳如何取的Java源代码文件中文件名和行号:)

在C/C++的程序,编译器提供了两个宏来支持取得源文件中的行号和文件名,这两个宏是__FILE__,__LINE__

你可以如下的方法打印行号和文件名

1.#include <stdio.h>
2.int main()
3.{
4. fprintf(stdout,"[%s:%d] Hello World!",__FILE__,__LINE__);
5. return 0;
6.}

但是在JAVA下没有这两个宏,那么我们如何来取得文件名和行号,翻阅JDK,我们找到StackTraceElement这个类。这个类可以从Throwable取得,另外也可以从Thread类取得,通过这些我写如下的一个打印行号的测试程序:

01.public class LineNo {
02. public static int getLineNumber() {
03. return Thread.currentThread().getStackTrace()[2].getLineNumber();
04. }
05.
06. public static String getFileName() {
07. return Thread.currentThread().getStackTrace()[2].getFileName();
08. }
09. public static void main(String args[]) {
10. System.out.println("["+getFileName()+":"+ getLineNumber()+"]"+"Hello World!");
11. }
12.}

留下一个问题,上面程序中的magic数字 2 代表什么含义呢?