Basic|Basic Guava Utilities-Preconditions

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; } }

【Basic|Basic Guava Utilities-Preconditions】上面代码中四个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

    推荐阅读