Google Guava学习笔记guava

Basic Guava Utilities-Preconditi

2016-09-05  本文已影响54人  Viking_Den

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类中方法的简介:

上一篇下一篇

猜你喜欢

热点阅读