Guava中提供了一個做參數檢查的工具類–Preconditions, 靜態導入這個類, 能夠大大地簡化代碼中對於參數的預判斷和處理.html
import static com.google.common.base.Preconditions;
在之前, 咱們須要判斷一個參數不爲空的話, 須要像下面這樣寫java
public void testMethod(Object obj) { if (obj == null) { throw new NullPointerException(); } // … other operations }
每次都要添加if語句來作判斷, 重複的工做會作好屢次. 使用Preconditions能夠簡化成下面這樣git
public void testMethod(Object obj) { Object other = checkNotNull(obj); // … other operations }
checkNotNull會檢查參數是否爲null, 當爲null的時候會拋出NullPointerException, 不然直接返回參數.app
checkNotNull, checkArgument和checkState, 都有三種形式的參數:wordpress
public static <T> T checkNotNull(T reference), 只包含須要判斷的對象, 無其餘多餘的參數, 拋出的異常不帶有任何異常信息工具
public static <T> T checkNotNull(T reference, @Nullable Object errorMessage), 包含一個錯誤信息的額外參數, 拋出的異常帶有errorMessage.toString()的異常信息this
public static <T> T checkNotNull(T reference, @Nullable String errorMessageTemplate, @Nullable Object… errorMessageArgs), printf風格的錯誤信息, 後面是變參, errorMessageTemplate可使用一些佔位符. 例如能夠這樣寫googlecheckArgument(i >= 0, 「Argument was %s but expected nonnegative」, i);
checkArgument(i < j, 「Expected i < j, but %s > %s」, i, j);
捕獲異常後能夠獲取自定義的詳細錯誤信息, 對於調試來講頗有幫助, 並且代碼也很簡潔. 例如,spa
Object obj = null; try { checkNotNull(obj, "cannot be null"); } catch(Exception e) { System.out.println(e.getMessage()); }
運行後能夠得到自定義的異常信息」cannot be null」..net
方法簽名 (不包含額外參數) | 功能描述 | 失敗時拋出的異常類型 |
checkArgument(boolean) | 檢查boolean是否爲真. 用做方法中檢查參數. | IllegalArgumentException |
checkNotNull(T) | 檢查value不爲null. 直接返回value. | NullPointerException |
checkState(boolean) | 檢查對象的一些狀態, 不依賴方法參數. 例如, Iterator能夠用來next是否在remove以前被調用. | IllegalStateException |
checkElementIndex(int index, int size) | 檢查index是否爲在一個長度爲size的list, string或array合法的範圍. index的範圍區間是[0, size)(包含0不包含size). 無需直接傳入list, string或array, 只需傳入大小. 返回index. |
IndexOutOfBoundsException |
checkPositionIndex(int index, int size) | 檢查位置index是否爲在一個長度爲size的list, string或array合法的範圍. index的範圍區間是[0, size)(包含0不包含size). 無需直接傳入list, string或array, 只需傳入大小. 返回index. |
IndexOutOfBoundsException |
checkPositionIndexes(int start, int end, int size) | 檢查[start, end)是一個長度爲size的list, string或array合法的範圍子集.伴隨着錯誤信息. | IndexOutOfBoundsException |
在靜態導入後, 方法很明確無歧義, checkNotNull能夠清楚地告訴你它是幹什麼的, 它會拋出怎樣的異常.
checkNotNull在驗證經過後直接返回, 能夠這樣方便地寫代碼: this.field = checkNotNull(field).
簡單而又強大的可變參數’printf’風格的自定義錯誤信息.
咱們建議將preconditions放置在單獨的行上, 這樣能夠在調試的時候清楚地指明哪一個precondition出現錯誤. 另外, 提供有幫助的錯誤信息也很是有用.
官方wiki: http://code.google.com/p/guava-libraries/wiki/GuavaExplained Preconditions: http://code.google.com/p/guava-libraries/wiki/PreconditionsExplained