關於Java assert關鍵字的使用,參考Stack Overflow的高票回答:html
What are some real life examples to understand the key role of assertions?java
|
Assertions (by way of the assert keyword) were added in Java 1.4. They are used to verify the correctness of an invariant in the code. They should never be triggered in production code, and are indicative of a bug or misuse of a code path. They can be activated at run-time by way of the An example:ide public Foo acquireFoo(int id) { Foo result = null; if (id > 50) { result = fooService.read(id); } else { result = new Foo(id); } assert result != null; return result; } |
這段話的翻譯是:ui
Java 1.4 加入了斷言(也就是assert關鍵字)。 它們被用來檢驗代碼中的不變條件的正確性。 它們不該該在生產環境中被觸發,而應該用來指示BUG或者代碼路徑的誤用。能夠經過在Java命令行加上-ea 選項來在運行時啓用它們,可是默認狀況下,它們是關閉的。命令行
一說,根據Oracle的官方文檔,assert不該該用來檢驗public方法的參數,而應該用拋異常來代替。翻譯
請注意,這裏說的是否是像網上的文章說的不使用assert關鍵字,規範的使用斷言能夠增長代碼可讀性,可是在生產環境中不該該觸發任何的assert條件。code
參考文獻: http://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.htmlhtm