Google Guava学习笔记——基础工具类Preconditions类的使用

  Preconditions类是一组静态方法用来验证我们代码的状态。Preconditons类很重要,它能保证我们的代码按照我们期望的执行,如果不是我们期望的,我们会立即得到反馈是哪里出来问题,现在我们使用Preconditions来保证我们代码的行为,并且对调试也非常方便。

  当然,你也可以自己写预处理的代码,就像下面一样:

if (someObj == null) {
        throw new IllegalArgumentException(" someObj must not be null");
    }

  但使用Preconditions类来处理参数为空的情况,会更加清晰可读:

Preconditions.checkNotNull(label, "Label can't not be null");

  下面的类演示了Preconditions类的使用:

  

package com.guava.felix;

import com.google.common.base.Preconditions;

public class PreconditionsDemo {

    private String label;

    private int[] values = new int[5];

    private int currentIndex;

    public PreconditionsDemo(String label) {
    this.label = Preconditions.checkNotNull(label, "Label can't not be null");
    }

    public void updateCurrentIndexValue(int index, int valueToSet) {
    // check index valid first
    this.currentIndex = Preconditions.checkElementIndex(index, values.length, "Index out of bounds for values.");
    // validate valueToSet
    Preconditions.checkArgument(valueToSet <= 100, "Value can't be more than 100");
    values[this.currentIndex] = valueToSet;
    }

    public void doOperation() {
    Preconditions.checkState(validateObjectState(), "Can't perform operation.");
    }

    private boolean validateObjectState() {
    return this.label.equalsIgnoreCase("open") && values[this.currentIndex] == 10;
    }

    public static void main(String[] args) {
    PreconditionsDemo demo = new PreconditionsDemo("open");

    demo.updateCurrentIndexValue(4, 10);

    demo.doOperation();

    }

}

 下面是例子中四个方法的总结:

  checkNotNull(T object, Object message): object对象不为空的话返回,否则抛出异常。

  checkElementIndex(int index, int size, Object message): index表示你要访问的数组,集合,字符串的位置,size表示的是长度,如果 index是有效的则返回,否则抛出异常;

  checkArgument(Boolean expression, Object message):这个方法根据传递进来的参数是否满足方法中的逻辑判断,如果符合,返回true,否则抛出异常。

  checkStatus(Boolean expression, Object message):这个方法没有参数,它判断一个对象的状态,期望返回true,否则抛出异常。

原文地址:https://www.cnblogs.com/IcanFixIt/p/4511949.html