JDK1.4中引入的一个新特性之一就是断言(assert),为程序的调试提供了强有力的支持,以下的文档根据SUNTEC内容及相关内容组成。
源代码:
/**
* Simple examples of the use of the new assertion feature in JDK1.4
*
* @author S.Ritter 16/7/2001
**/
public class AssertExample {
public static void main(String[] args) {
int x = 10;
if (args.length > 0) {
try {
x = Integer.parseInt(args[0]);
} catch (NumberFormatException nfe) {
/* Ignore */
}
}
System.out.println("Testing assertion that x == 10");
assert x == 10:"Our assertion failed";
System.out.println("Test passed");
}
}
由于引入了一个新的关键字,所以在编译的时候就需要增加额外的参数,要编译成功,必须使用JDK1.4的javac并加上参数'-source 1.4',例如可以使用以下的命令编译上面的代码:
javac -source 1.4 AssertExample.java
以上程序运行使用断言功能也需要使用额外的参数(并且需要一个数字的命令行参数),例如:
java -ea AssertExample 1
程序的输出为:
Testing assertion that x == 10
Exception in thread "main" java.lang.AssertionError: Our assertion failed
at AssertExample.main(AssertExample.java:20)