java获取行号

package org.lr.explore;

import java.text.SimpleDateFormat;
import java.util.Date;

public class LineNumberDemo {

	/**
	 * 如何获取当前语句在java文件中所处的行号
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		Logger logger = new Logger(LineNumberDemo.class);
		logger.debug("调试日志");
		logger.info("信息日志");
	}
	
	public String getLineNumber(){
		StackTraceElement[] ste = (Thread.currentThread()).getStackTrace();
		return ste[1].getLineNumber()+"";
	}
}

class Logger{
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS");
	private String cn = "";
	public Logger(Class<?> c){
		cn = c.getSimpleName()+".java";
	}
	
	private String getTime(){
		return sdf.format(new Date());
	}
	
	public void debug(Object msg){
		StackTraceElement[] ste = (Thread.currentThread()).getStackTrace();
		long line = ste[2].getLineNumber();
		System.out.println(getTime()+" DEBUG: "+msg+"("+cn+":"+line+")");
	}
	
	public void info(Object msg){
		StackTraceElement[] ste = (new Exception()).getStackTrace();
		long line = ste[1].getLineNumber();
		System.out.println(getTime()+" INFO: "+msg+"("+cn+":"+line+")");
	}
}

输出:

2016-04-12 05:51:09 303 DEBUG: 调试日志(LineNumberDemo.java:15)
2016-04-12 05:51:09 304 INFO: 信息日志(LineNumberDemo.java:16)

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>