本文实例讲述了Java编程实现获取当前代码行行号的方法。分享给大家供大家参考,具体如下:
最近的项目中,为了实现自定义的log类,能够输出具体的代码行行号,我通过使用StackTraceElement对象实现了。
具体内容请参考下面的Demo代码。这里指出需要注意的几个问题:
1. 程序中返回的代码行行号,是新建StackTrackElement对象的那一行。
2. 可以通过传参的方法实现输出特定行行号。
具体实现代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
/** * */ package leo.demo.training; /** * Get current java file name and current code line number * @author Leo Xie */ public class CurrentLine { /** * @param args */ public static void main(String[] args) { StackTraceElement ste1 = null ; // get current thread and its related stack trace StackTraceElement[] steArray = Thread.currentThread().getStackTrace(); int steArrayLength = steArray.length; String s = null ; // output all related info of the existing stack traces if (steArrayLength== 0 ) { System.err.println( "No Stack Trace." ); } else { for ( int i= 0 ; i<steArrayLength; i++) { System.out.println( "Stack Trace-" + i); ste1 = steArray[i]; s = ste1.getFileName() + ": Line " + ste1.getLineNumber(); System.out.println(s); } } // the following code segment will output the line number of the "new " clause // that's to say the line number of "StackTraceElement ste2 = new Throwable().getStackTrace()[0];" StackTraceElement ste2 = new Throwable().getStackTrace()[ 0 ]; System.out.println(ste2.getFileName() + ": Line " + ste2.getLineNumber()); // the following clause will output the line number in the external method "getLineInfo()" System.out.println(getLineInfo()); // the following clause will output its current line number System.out.println(getLineInfo( new Throwable().getStackTrace()[ 0 ])); } /** * return current java file name and code line number * @return String */ public static String getLineInfo() { StackTraceElement ste3 = new Throwable().getStackTrace()[ 0 ]; return (ste3.getFileName() + ": Line " + ste3.getLineNumber()); } /** * return current java file name and code line name * @return String */ public static String getLineInfo(StackTraceElement ste4) { return (ste4.getFileName() + ": Line " + (ste4.getLineNumber())); } } |
希望本文所述对大家java程序设计有所帮助。
原文链接:http://www.cnblogs.com/xxpal/articles/1209378.html