溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

JDK1.4新特性斷言怎么用

發(fā)布時間:2021-12-17 13:41:07 來源:億速云 閱讀:174 作者:小新 欄目:編程語言

小編給大家分享一下JDK1.4新特性斷言怎么用,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

JDK1.4中引入的一個新特性之一就是斷言(assert),為程序的調(diào)試提供了強有力的支持,以下的文檔根據(jù)SUNTEC內(nèi)容及相關(guān)內(nèi)容組成。
源代碼:

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");
}
}

由于引入了一個新的關(guān)鍵字,所以在編譯的時候就需要增加額外的參數(shù),要編譯成功,必須使用JDK1.4的javac并加上參數(shù)´-source 1.4´,例如可以使用以下的命令編譯上面的代碼:
javac -source 1.4 AssertExample.java

以上程序運行使用斷言功能也需要使用額外的參數(shù)(并且需要一個數(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,因此斷言功能使得程序運行時拋出斷言錯誤,注意是錯誤,這意味著程序發(fā)生嚴(yán)重錯誤并且將強制退出。斷言使用boolean值,如果其值不為true則拋出AssertionError并終止程序的運行。
由于程序員的問題,斷言的使用可能會帶來副作用,例如:
boolean isEnable=false;
//...
assert isEnable=true;

這個斷言的副作用是因為它修改程序變量的值并且沒有拋出錯誤,這樣的錯誤如果不細(xì)心檢查很難發(fā)現(xiàn)。但是同時我們可以根據(jù)以上的副作用得到一個有用的特性,根據(jù)它測試是否將斷言打開了。

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ù)運行上面的程序,則控制臺將輸出:

Exception in thread "main" java.lang.RuntimeException: Assertions should be enab
le
at AssertExample.main(AssertExample.java:14)

以上是“JDK1.4新特性斷言怎么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

jdk
AI