Preconditions類包含有許多的靜態(tài)方法來(lái)檢查代碼的狀態(tài)顶岸。
你可以自己來(lái)實(shí)現(xiàn)預(yù)置的條件判斷,像下面的代碼段:
if(someObj == null){
throw new IllegalArgumentException(" someObj must not be null");
}
但是仑性,使用Precondition(靜態(tài)導(dǎo)入)類來(lái)實(shí)現(xiàn)同樣的功能适室,相當(dāng)?shù)暮?jiǎn)潔:
checkNotNull(someObj,"someObj must not be null");
下面是Precondition類的幾種常用方法示例:
public class PreconditionExample {
private String label;
private int[] values = new int[5];
private int currentIndex;
public PreconditionExample(String label) {
//returns value of object if not null
this.label = checkNotNull(label,"Label can''t be null");
}
public void updateCurrentIndexValue(int index, int valueToSet) {
//Check index valid first
this.currentIndex = checkElementIndex(index, values.length,"Index out of bounds for values");
//Validate valueToSet
checkArgument(valueToSet <= 100,"Value can't be more than 100");
values[this.currentIndex] = valueToSet;
}
public void doOperation(){
checkState(validateObjectState(),"Can't perform operation");
}
private boolean validateObjectState(){
return this.label.equalsIgnoreCase("open") && values[this.currentIndex]==10;
}
}
上面代碼中四個(gè)Precondition類中方法的簡(jiǎn)介:
- checkNotNull (T object, Object message): 如果object不為空,直接返回object秆撮;否則,拋出NullPointerException異常逻恐。
- checkElementIndex (int index, int size, Object message): 如果index的值在給定的數(shù)組像吻、集合和字符的長(zhǎng)度size范圍之類,則返回index复隆;否則拨匆,拋出IndexOutOfBoundsException異常。
- checkArgument (Boolean expression, Object message): 此方法接受一個(gè)返回值為boolean類型的expression表達(dá)式挽拂,如果表達(dá)式不為true惭每,則拋出IllegalArgumentException異常。
- checkState (Boolean expression, Object message):同checkArgument