在項目中,大神們用了Guava,在這裡學習一下。
在網上找了一些資料,有的很不錯,想直接轉載來着,但是發現其中有些問題,決定自己
簡單的記錄一下。
1.為什麼使用Preconditions
我們在項目中,經常需要對參數進行校驗,非空啊,不能為NULL啊,大于0啊,小于100啦......
還記得之前分享過一篇部落格Bean Validation,是使用注解的方式,對參數進行一些校驗
而Google的這個工具類封裝了一些靜态方法,在項目中直接拿來做一些基本判斷,很友善
2.簡單示例
先看一下API
其實,根據API,根據方法名稱,就可以大概知道方法是什麼意思了
這裡我隻說明兩個網上部落格中的誤解吧
/**
* Ensures that {@code index} specifies a valid <i>element</i> in an array,
* list or string of size {@code size}. An element index may range from zero,
* inclusive, to {@code size}, exclusive.
*
* @param index a user-supplied index identifying an element of an array, list
* or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is not
* less than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkElementIndex(
int index, int size, @Nullable String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(badElementIndex(index, size, desc));
}
return index;
}
看這個方法,驗證index是否在指定的Array或List的長度區間内,index有效區間是 0 <= index < size
/**
* Ensures that {@code index} specifies a valid <i>position</i> in an array,
* list or string of size {@code size}. A position index may range from zero
* to {@code size}, inclusive.
*
* @param index a user-supplied index identifying a position in an array, list
* or string
* @param size the size of that array, list or string
* @param desc the text to use to describe this index in an error message
* @return the value of {@code index}
* @throws IndexOutOfBoundsException if {@code index} is negative or is
* greater than {@code size}
* @throws IllegalArgumentException if {@code size} is negative
*/
public static int checkPositionIndex(
int index, int size, @Nullable String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc));
}
return index;
}
這個方法,和上一個差不多,但是 index的有效區間是不一樣的 , 0 < = index < = size ,在這裡index是可以和size相等的
網上好多的部落格都沒寫明白,在這裡記下來,提醒大家。