前置條件:讓方法調用的前置條件判斷更簡單。
沒有額外參數:抛出的異常中沒有錯誤消息;
有一個object對象作為額外參數:抛出的異常使用object.tostring() 作為錯誤消息;
有一個string對象作為額外參數,并且有一組任意數量的附加object對象:這個變種處理異常消息的方式有點類似printf,但考慮gwt的相容性和效率,隻支援%s訓示符。例如:
<code>1</code>
<code>checkargument(i >= </code><code>0</code><code>, </code><code>"argument was %s but expected nonnegative"</code><code>, i);</code>
<code>2</code>
<code>checkargument(i < j, </code><code>"expected i < j, but %s > %s"</code><code>, i, j);</code>
<b>方法聲明(不包括額外參數)</b><b></b>
<b>描述</b><b></b>
<b>檢查失敗時抛出的異常</b><b></b>
<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/preconditions.html#checkargument(boolean)">checkargument(boolean)</a>
檢查boolean是否為true,用來檢查傳遞給方法的參數。
illegalargumentexception
<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/preconditions.html#checknotnull(t)">checknotnull(t)</a>
檢查value是否為null,該方法直接傳回value,是以可以内嵌使用checknotnull。
nullpointerexception
<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/preconditions.html#checkstate(boolean)">checkstate(boolean)</a>
用來檢查對象的某些狀态。
illegalstateexception
<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/preconditions.html#checkelementindex(int,%20int)">checkelementindex(int index, int size)</a>
檢查index作為索引值對某個清單、字元串或數組是否有效。index>=0 && index<size *
indexoutofboundsexception
<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/preconditions.html#checkpositionindex(int,%20int)">checkpositionindex(int index, int size)</a>
檢查index作為位置值對某個清單、字元串或數組是否有效。index>=0 && index<=size *
<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/preconditions.html#checkpositionindexes(int,%20int,%20int)">checkpositionindexes(int start, int end, int size)</a>
檢查[start, end]表示的位置範圍對某個清單、字元串或數組是否有效*
譯者注:
*索引值常用來查找清單、字元串或數組中的元素,如list.get(int), string.charat(int)
*位置值和位置範圍常用來截取清單、字元串或數組,如list.sublist(int,int), string.substring(int)
在靜态導入後,guava方法非常清楚明晰。checknotnull清楚地描述做了什麼,會抛出什麼異常;
checknotnull直接傳回檢查的參數,讓你可以在構造函數中保持字段的單行指派風格:this.field = checknotnull(field)
在編碼時,如果某個值有多重的前置條件,我們建議你把它們放到不同的行,這樣有助于在調試時定位。此外,把每個前置條件放到不同的行,也可以幫助你編寫清晰和有用的錯誤消息。