1. 程式人生 > >如何在Java中獲取當前程式碼行行號

如何在Java中獲取當前程式碼行行號

為了實現自定義的log類,能夠輸出具體的程式碼行行號,我通過使用StackTraceElement物件實現了。


這裡指出需要注意的幾個問題:
1. 程式中返回的程式碼行行號,是新建StackTrackElement物件的那一行。
2. 可以通過傳參的方法實現輸出特定行行號。具體實現見程式碼。


1/** 


2 *
3 */
4package leo.demo.training;
5
6/**


7 * Get current java file name and current code line number
8 * @author Leo Xie
9 */
10public class CurrentLine {
11 /** *//** http://www.mscto.com
12 * @param args
13 */
14 public static void main(String[] args) {
15 StackTraceElement ste1 = null;
16
17 // get current thread and its related stack trace
18 StackTraceElement[] steArray = Thread.currentThread().getStackTrace();
19 int steArrayLength = steArray.length;
20
21 String s = null;


22
23 // output all related info of the existing stack traces
24 if(steArrayLength==0) {
軟體開發網

25 System.err.println("No Stack Trace.");
26 } else {
27 for (int i=0; i<steArrayLength; i++) {
28 System.out.println("Stack Trace-" + i);
29 ste1 = steArray[i];
30 s = ste1.getFileName() + ": Line " + ste1.getLineNumber();


31 System.out.println(s);
32 }
33 }
34 // the following code segment will output the line number of the "new " clause
35 // that's to say the line number of "StackTraceElement ste2 = new Throwable().getStackTrace()[0];"
36 StackTraceElement ste2 = new Throwable().getStackTrace()[0]; http://www.mscto.com
37 System.out.println(ste2.getFileName() + ": Line " + ste2.getLineNumber());
38 // the following clause will output the line number in the external method "getLineInfo()"

39 System.out.println(getLineInfo());
40 // the following clause will output its current line number
41 System.out.println(getLineInfo(new Throwable().getStackTrace()[0]));
42 }
43
44 /** *//**
45 * return current java file name and code line number
46 * @return String
47 */
48 public static String getLineInfo() {


49 StackTraceElement ste3 = new Throwable().getStackTrace()[0];
50 return (ste3.getFileName() + ": Line " + ste3.getLineNumber()); http://www.mscto.com
51 }
52
53 /** *//** http://www.mscto.com
54 * return current java file name and code line name
55 * @return String
56 */
57 public static String getLineInfo(StackTraceElement ste4) {

58 return (ste4.getFileName() + ": Line " + (ste4.getLineNumber()));
59 }
60}