PreConditions(先決條件)
- checkArgument(boolean expression, [String errorMsgTemplate], [String errorMsgArgs]):expression如果為false,則抛出IllegalArgumentException異常,并輸出錯誤消息
Preconditions.checkArgument( > ); // throw IllegalArgumentException Preconditions.checkArgument( > , "1 lower than 2"); // throw IllegalArgumentException: 1 lower than 2 Preconditions.checkArgument( > , "%s lower than %s", , ); // throw IllegalArgumentException: 1 lower than 2
- T checkNotNul (T ref):如果ref為null,則抛出NullPointerException;否則傳回ref的引用(該方法的其他幾種重載可以自定義輸出錯誤消息)
String s1 = Preconditions.checkNotNull("1"); s1; // 1 String s2 = Preconditions.checkNotNull(null);// throw NullPointerException
- void checkState (boolean expression):用法與checkArgument相同,隻不過抛出的是IllegalStateException異常
- int checkElementIndex (int index, int size):檢查索引是否在[0, size)之間,不在則抛出IndexOutOfBoundsException異常
Preconditions.checkElementIndex(, ); // throw IndexOutOfBoundsException: index (3) must be less than size (3)
- int checkPositionIndex (int index, int size):檢查索引是否在[0, size]之間,不在則抛出IndexOutOfBoundsException異常
- void checkPositionIndexes (int start, int end, int size):檢查[start, end)是否在[0, size]之間,不在則抛出IndexOutOfBoundsException異常
- 使用優點:
- 語義明确
- 抛出的異常明确
- 可以自定義錯誤消息的格式
- 由于方法在校驗後傳回了參數本身,是以可以在寫在一行裡,簡化代碼