Java編程實現獲取當前代碼行行號的方法示例
本文實例講述了Java編程實現獲取當前代碼行行號的方法。分享給大家供大家參考,具體如下:
最近的項目中,為了實現自定義的log類,能夠輸出具體的代碼行行號,我通過使用StackTraceElement對象實現了。
具體內容請參考下面的Demo代碼。這里指出需要注意的幾個問題:
1. 程序中返回的代碼行行號,是新建StackTrackElement對象的那一行。
2. 可以通過傳參的方法實現輸出特定行行號。
具體實現代碼:
/** * */ 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算法相關內容感興趣的讀者可查看本站專題:《Java數學運算技巧總結》、《Java數據結構與算法教程》、《Java操作DOM節(jié)點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
相關文章
Java微服務分布式調度Elastic-job環(huán)境搭建及配置
Elastic-Job在配置中提供了JobEventConfiguration,支持數據庫方式配置,會在數據庫中自動創(chuàng)建JOB_EXECUTION_LOG和JOB_STATUS_TRACE_LOG兩張表以及若干索引,來記錄作業(yè)的相關信息2023-02-02Java ThreadLocal詳解_動力節(jié)點Java學院整理
ThreadLocal,很多地方叫做線程本地變量,也有些地方叫做線程本地存儲,本文會詳細的介紹一下,有興趣的可以了解一下2017-06-06Java集合中的CopyOnWriteArrayList使用詳解
這篇文章主要介紹了Java集合中的CopyOnWriteArrayList使用詳解,CopyOnWriteArrayList是ArrayList的線程安全版本,從他的名字可以推測,CopyOnWriteArrayList是在有寫操作的時候會copy一份數據,然后寫完再設置成新的數據,需要的朋友可以參考下2023-12-12Spring中的FactoryBean與ObjectFactory詳解
這篇文章主要介紹了Spring中的FactoryBean與ObjectFactory詳解,FactoryBean是一種特殊的bean,本身又是個工廠,實現了FactoryBean的bean會被注冊到容器中,需要的朋友可以參考下2023-12-12