7 System.out.printf("Filename is = %s\n",f.getFileName());
8 System.out.printf("LineNumber is = %d\n",f.getLineNumber());
9 System.out.printf("ClassName is = %s\n",f.getClassName());
10 System.out.printf("Methodname is = %s\n",f.getMethodName());
11 System.out.printf("isNativeMethod = %s\n",f.isNativeMethod() "true" : "false");
12 }
13 }
14 }
也可以直接通过Throwable对象函数当前函数的运行栈信息,见如下代码:
1 也可以直接通过Throwable对象函数当前函数的运行栈信息,见如下代码:
2 public static void main(String[] args) {
3 Throwable e = new Throwable();
4 StackTraceElement[] frames = e.getStackTrace();
5 for (StackTraceElement f : frames) {
6 System.out.printf("Filename is = %s\n",f.getFileName());
7 System.out.printf("LineNumber is = %d\n",f.getLineNumber());
8 System.out.printf("ClassName is = %s\n",f.getClassName());
9 System.out.printf("Methodname is = %s\n",f.getMethodName());
10 System.out.printf("isNativeMethod = %s\n",f.isNativeMethod() "true" : "false");
11 }
12 }
13 /* 输入如下:
14 Filename is = TestMain.java
15 LineNumber is = 3
16 ClassName is = TestMain
17 Methodname is = main
18 isNativeMethod = false */
C++语言本身并未提供这样的方法,只是提供了__FUNCTION__、__LINE__、__FILE__这样的3个宏来获取当前函数的函数名、行号和文件名,但是无法得到调用栈信息,如果确实需要这样的信息,只能通过操作系统的工具包来协助完成(仅针对Debug版本),目前Windows(vc)和Linux(gcc)都提供这样的开发包。
2. 断言:是主要用于开发、调试和系统集成测试期间进行Debug的一种方式和技巧,语法如下:
assert condition OR assert condition : expression
其中assert为关键字,当condition为false时,程序运行中断,同时报出指定的错误信息,如果使用assert的后面一种形式,expression的结果将会同时输出,这样更有助于错误的判断,见如下两种代码形式:
1 public static void main(String[] args) {
2 int a = 5;
3 assert a > 10 : a;
4 System.out.println("Ok.");
5 }
6 /* 输出结果:
7 Exception in thread "main" java.lang.AssertionError: 5
8 at TestMain.main(TestMain.java:4)
9 */
10 public static void main(String[] args) {
11 int[] a = null;
12 assert a != null;
13 System.out.println("Ok.");
14 }
15 /* 输出结果:
16 Exception in thread "main" java.lang.AssertionError
17 at TestMain.main(TestMain.java:4)
18 */
在eclipse中,缺省情况下断言是被禁用的,如果需要开启断言,则需要在Run(Debug) As->Run(Debug) Configurations...->Arguments->VM arguments中添加"-enableassertions" 运行期参数。如果断言被禁用,assert中的代码不会被执行,因此在系统发布后也不会影响程序的运行时效率。使用者也可以通过该命令行参数-ea:MyClass -ea:com.mypackage.mylib 来指定需要启用断言的class和package,如果启用的是package,那么该包内的所有class都将启用断言。在C++中,是依靠crt中的assert(cond)函数来实现的,如果cond为false,程序将会立即停止,但是在使用前首先需要保证assert.h文件被包含进当前文件,再有就是当前编译的程序必须是Debug版本,对于Release版本,无论Win32和Linux,断言的语句都将不会被执行。
作者:Stephen_Liu