Java编程实现获取当前代码行行号的方法示例
时间:2021-03-15 09:52:26|栏目: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节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。
上一篇:Springboot JPA 枚举Enum类型存入到数据库的操作
栏 目:JAVA代码
下一篇:使用spring实现邮件的发送实例(含测试,源码,注释)
本文地址:http://www.codeinn.net/misctech/81248.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




