天天看點

Java assert 關鍵字使用

關于Java assert關鍵字的使用,參考Stack Overflow的高票回答:

What are some real life examples to understand the key role of assertions?

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 

-ea

option on the 

java

 command, but are not turned on by default.

An example:

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

這段話的翻譯是:

Java 1.4 加入了斷言(也就是assert關鍵字)。 它們被用來檢驗代碼中的不變條件的正确性。 它們不應該在生産環境中被觸發,而應該用來訓示BUG或者代碼路徑的誤用。可以通過在Java指令行加上-ea 選項來在運作時啟用它們,但是預設情況下,它們是關閉的。

一說,根據Oracle的官方文檔,assert不應該用來檢驗public方法的參數,而應該用抛異常來代替。

請注意,這裡說的是不是像網上的文章說的不使用assert關鍵字,規範的使用斷言可以增加代碼可讀性,但是在生産環境中不應該觸發任何的assert條件。

參考文獻: http://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html

版權聲明:本文為CSDN部落客「weixin_33940102」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。

原文連結:https://blog.csdn.net/weixin_33940102/article/details/92322067