获取当前运行代码的类名,方法名,行号

/*   
 * 1.获取当前运行代码的类名,方法名,行号,主要是通过java.lang.StackTraceElement类
 * 
 * 2. 
 *   [1]获得调用者的方法名, 同new Throwable
 *         String _methodName = new Exception().getStackTrace()[1].getMethodName();
 *   [0]获得当前的方法名, 同new Throwable
 *         String _thisMethodName = new Exception().getStackTrace()[0].getMethodName();
 * */
public class StackTraceElementTest {
	
	public static void main(String[] args) {
		System.out.println("line1: " + new Throwable().getStackTrace()[0].getLineNumber());
		System.out.println("line2: " + getLineInfo());
		System.out.println("line3: " + getTraceInfo());

		StackTraceElement ste1 = null;
		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);
			}
		}
	}

	public static String getTraceInfo(){  
                StringBuffer sb = new StringBuffer();   
          
                StackTraceElement[] stacks = new Throwable().getStackTrace();  
                int stacksLen = stacks.length;  
                sb.append("class: " ).append(stacks[1].getClassName())
                .append("; method: ").append(stacks[1].getMethodName())
                .append("; number: ").append(stacks[1].getLineNumber());  
          
                return sb.toString();  
         }  
	
	public static String getLineInfo() {
                StackTraceElement ste = new Throwable().getStackTrace()[1];
                return ste.getFileName() + ": Line " + ste.getLineNumber();
         }
	
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值