Preconditions比較簡(jiǎn)單的
前置條件:讓方法調(diào)用的前置條件判斷更簡(jiǎn)單。
準(zhǔn)備工作
官方倉(cāng)庫(kù):https://github.com/google/guava
在線wiki:
https://github.com/google/guava/wiki/PreconditionsExplained
com.google.common.base.Preconditions
| 方法聲明 | 描述 | 失敗時(shí)拋出的異常 |
|---|---|---|
checkArgument(boolean) |
檢查boolean是否為true,傳入false拋出異常 | IllegalArgumentException |
checkNotNull(T) |
檢查<T> value為null直接拋出異常,否則直接返回value。 | NullPointerException |
checkState(boolean) |
用來(lái)檢查對(duì)象的某些狀態(tài)。 | IllegalStateException |
checkElementIndex(int index, int size) |
檢查index作為索引值對(duì)某個(gè)列表、字符串或數(shù)組是否有效。index>=0 && index<size
|
IndexOutOfBoundsException |
checkPositionIndex(int index, int size) |
檢查index作為位置值對(duì)某個(gè)列表、字符串或數(shù)組是否有效。index>=0 && index<=size
|
IndexOutOfBoundsException |
checkPositionIndexes(int start, int end, int size) |
檢查[start, end]表示的位置范圍對(duì)某個(gè)列表、字符串或數(shù)組是否有效 | IndexOutOfBoundsException |
Preconditions.checkArgument(false);Preconditions.checkArgument(false,"this is a test!"); //this is a test!
Preconditions.checkArgument(false,"%s is a %s","hjh","pig"); //hjh is a pig
Preconditions.checkElementIndex(20, 10); //java.lang.IndexOutOfBoundsException: index (20) must be less than size (10)
Preconditions.checkPositionIndex(20, 10, "desc !!!!"); //java.lang.IndexOutOfBoundsException: desc !!!! (20) must not be greater than size (10)
Preconditions.checkPositionIndex(20, 10); //java.lang.IndexOutOfBoundsException: index (20) must not be greater than size (10)
Preconditions.checkState(false); // java.lang.IllegalStateException
Preconditions.checkNotNull(1);//1
Preconditions.checkNotNull(null,"is null"); //java.lang.NullPointerException: is null
Preconditions.checkNotNull(null, "%s is null !", "object"); //java.lang.NullPointerException: object is null !