日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
JDK1.4特性assert詳解

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

源代碼:

 
 
 
  1. /**  
  2. * Simple examples of the use of the new assertion feature in JDK1.4  
  3. *  
  4. * @author S.Ritter 16/7/2001  
  5. **/ 
  6. public class AssertExample {  
  7. public static void main(String[] args) {  
  8. int x = 10;  
  9. if (args.length > 0) {  
  10. try {  
  11. x = Integer.parseInt(args[0]);  
  12. } catch (NumberFormatException nfe) {  
  13. /* Ignore */ 
  14. }  
  15. }  
  16. System.out.println("Testing assertion that x == 10");  
  17. assert x == 10:"Our assertion failed";  
  18. System.out.println("Test passed");  
  19. }  

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

javac -source 1.4 AssertExample.java

以上程序運行使用斷言功能也需要使用額外的參數(shù)(并且需要一個數(shù)字的命令行參數(shù)),例如:

java -ea AssertExample 1

程序的輸出為:

 
 
 
  1. Testing assertion that x == 10 
  2. Exception in thread "main" java.lang.AssertionError: Our assertion failed  
  3. at AssertExample.main(AssertExample.java:20) 

由于輸入的參數(shù)不等于10,因此斷言功能使得程序運行時拋出斷言錯誤,注意是錯誤,這意味著程序發(fā)生嚴重錯誤并且將強制退出。斷言使用boolean值,如果其值不為true則拋出AssertionError并終止程序的運行。

由于程序員的問題,斷言的使用可能會帶來副作用,例如:

 
 
 
  1. boolean isEnable=false;  
  2. //...  
  3. assert isEnable=true; 

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

 
 
 
  1. /**  
  2. * Simple examples test enable assertion feature in JDK1.4  
  3. *  
  4. * @author Cherami 25/4/2002  
  5. **/ 
  6. public class AssertExample2 {  
  7. public static void main(String[] args) {  
  8. boolean assertEnable=false;  
  9. assert assertEnable=true;  
  10. if (assertEnable==false)  
  11. {  
  12. throw new RuntimeException("Assertions should be enable");  
  13. }  
  14. }  

如果我們不使用-ea參數(shù)運行上面的程序,則控制臺將輸出:

 
 
 
  1. Exception in thread "main"   
  2. java.lang.RuntimeException: Assertions should be enable at AssertExample.main(AssertExample.java:14) 

JDK1.4特性assert詳解就介紹到這里,通過這個介紹希望你對JDK1.4特性assert有所了解。

【編輯推薦】

  1. JDK1.4在Windows下的環(huán)境配置
  2. JDK1.6在LINUX下的安裝配置
  3. JDK1.5中新的語言特征淺析
  4. JDK、SDK、JRE、JVM概念詳解
  5. JDK1.6的十大技術(shù)淺談

網(wǎng)站標題:JDK1.4特性assert詳解
文章來源:http://m.5511xx.com/article/cdheeop.html