Preconditions類包含有許多的靜態方法來檢查代碼的狀態。
你可以自己來實現預置的條件判斷,像下面的代碼段:
if(someObj == null){
throw new IllegalArgumentException(" someObj must not be null");
}
但是,使用Precondition(靜態導入)類來實現同樣的功能,相當的簡潔:
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;
}
}
上面代碼中四個Precondition類中方法的簡介:
- checkNotNull (T object, Object message): 如果object不為空,直接返回object;否則,拋出NullPointerException異常。
- checkElementIndex (int index, int size, Object message): 如果index的值在給定的數組、集合和字符的長度size范圍之類,則返回index;否則,拋出IndexOutOfBoundsException異常。
- checkArgument (Boolean expression, Object message): 此方法接受一個返回值為boolean類型的expression表達式,如果表達式不為true,則拋出IllegalArgumentException異常。
- checkState (Boolean expression, Object message):同checkArgument