标签:
C语言中有__LINE__、__FILE__表示行号和文件名称,在Java中可以通过StackTraceElement类实现类似的功能。如:
System.out.println(Thread.currentThread().getStackTrace()[1].getClassName()); System.out.println(Thread.currentThread().getStackTrace()[1].getFileName()); System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); System.out.println(Thread.currentThread().getStackTrace()[1].getLineNumber()); System.out.println(new Throwable().getStackTrace()[0].getFileName()); System.out.println(new Throwable().getStackTrace()[0].getLineNumber());
package test; public class StackTraceElementTest { public void methodA() { methodB(); } public void methodB() { StackTraceElement[] stacks = Thread.currentThread().getStackTrace(); for(StackTraceElement s : stacks) { System.out.println("*******************"); System.out.println("fileName :"+s.getFileName()); System.out.println("methodName:"+s.getMethodName()); System.out.println("lineNumber:"+s.getLineNumber()); System.out.println("["+s+"]"); } } public static void main(String[] args) { new StackTraceElementTest().methodA(); } } /* output: ******************* fileName :Thread.java methodName:getStackTrace lineNumber:1479 [java.lang.Thread.getStackTrace(Thread.java:1479)] ******************* fileName :StackTraceElementTest.java methodName:methodB lineNumber:9 [test.StackTraceElementTest.methodB(StackTraceElementTest.java:9)] ******************* fileName :StackTraceElementTest.java methodName:methodA lineNumber:6 [test.StackTraceElementTest.methodA(StackTraceElementTest.java:6)] ******************* fileName :StackTraceElementTest.java methodName:main lineNumber:20 [test.StackTraceElementTest.main(StackTraceElementTest.java:20)] *///:)GL
标签:
原文地址:http://www.cnblogs.com/liangyonglu/p/5563851.html