本文實例講述了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