源代碼:
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");
}
}
由于引入了一個(gè)新的關(guān)鍵字,所以在編譯的時(shí)候就需要增加額外的參數(shù),要編譯成功,必須使用JDK1.4的javac并加上參數(shù)'-source 1.4',例如可以使用以下的命令編譯上面的代碼:
javac -source 1.4 AssertExample.java
以上程序運(yùn)行使用斷言功能也需要使用額外的參數(shù)(并且需要一個(gè)數(shù)字的命令行參數(shù)),例如:
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)
由于輸入的參數(shù)不等于10,因此斷言功能使得程序運(yùn)行時(shí)拋出斷言錯(cuò)誤,注意是錯(cuò)誤,這意味著程序發(fā)生嚴(yán)重錯(cuò)誤并且將強(qiáng)制退出。斷言使用boolean值,如果其值不為true則拋出AssertionError并終止程序的運(yùn)行。
由于程序員的問(wèn)題,斷言的使用可能會(huì)帶來(lái)副作用,例如:
boolean isEnable=false;
//...
assert isEnable=true;
這個(gè)斷言的副作用是因?yàn)樗薷某绦蜃兞康闹挡⑶覜](méi)有拋出錯(cuò)誤,這樣的錯(cuò)誤如果不細(xì)心檢查很難發(fā)現(xiàn)。但是同時(shí)我們可以根據(jù)以上的副作用得到一個(gè)有用的特性,根據(jù)它測(cè)試是否將斷言打開(kāi)了。
public class AssertExample2 {
public static void main(String[] args) {
boolean assertEnable=false;
assert assertEnable=true;
if (assertEnable==false){
throw new RuntimeException("Assertions should be enable");
}
}
}
如果我們不使用-ea參數(shù)運(yùn)行上面的程序,則控制臺(tái)將輸出:
Exception in thread "main" java.lang.RuntimeException:
Assertions should be enab
le
at AssertExample.main(AssertExample.java:14)