天天看點

google guava的Preconditions使用

google guava的base包中提供的Preconditions類用來友善的做參數的校驗,他主要提供如下方法:

  1. checkArgument 接受一個boolean類型的參數和一個可選的errorMsg參數,這個方法用來判斷參數是否符合某種條件,符合什麼條件google guava不關心,在不符合條件時會抛出IllegalArgumentException異常
  2. checkState 和checkArgument參數和實作基本相同,從字面意思上我們也可以知道這個方法是用來判斷狀态是否正确的,如果狀态不正确會抛出IllegalStateException異常
  3. checkNotNull方法用來判斷參數是否不是null,如果為null則會抛出NullPointerException空指針異常
  4. checkElementIndex方法用來判斷使用者傳入的數組下标或者list索引位置,是否是合法的,如果不合法會抛出IndexOutOfBoundsException
  5. checkPositionIndexes方法的作用和checkElementIndex方法相似,隻是此方法的索引範圍是從0到size包括size,而上面的方法不包括size。

下面我們看一個具體的使用示例:

package cn.outofmemory.guava.base;

import com.google.common.base.Preconditions;

public class PreconditionsDemo {
    public static void main(String[] args) {
        PreconditionsDemo demo = new PreconditionsDemo();
        demo.doSomething("Jim", 19, "hello world, hello java");
    }

    public void doSomething(String name, int age, String desc) {
        Preconditions.checkNotNull(name, "name may not be null");
        Preconditions.checkArgument(age >= 18 && age < 99, "age must in range (18,99)");
        Preconditions.checkArgument(desc !=null && desc.length() < 10, "desc too long, max length is ", 10);

        //do things
    }
}
      

上面例子中的doSomething()方法的開頭我們調用了三次Preconditions的方法,來對參數做校驗。

看似Preconditions實作很簡單,他的意義在于為我們提供了同一的參數校驗,并對不同的異常情況抛出合适類型的異常,并對異常資訊做格式化

繼續閱讀