在編寫程序的時候,很多時候都需要檢查輸入的參數是否符合我們的需要,比如人的年齡需要大于0,名字不能為空;如果不符合這兩個要求,我們將認為這個對象是不合法的,這時候我們需要編寫判斷這些參數是否合法的函數,我們可能這樣寫:
~~~
package com.wyp;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: 過往記憶
* Blog:http://www.iteblog.com
* Date: 13-7-24
* Time: 下午9:02
*/
public class TestObject {
List personList = new ArrayList();
public void addPerson(Person person) {
if (check(person)) {
personList.add(person);
}
}
private boolean check(Person person) {
if (person.getAge() > 0 && person.getName() != null) {
return true;
}
return false;
}
}
~~~
這樣看起來很不錯,但是如果還有很多對象需要進行驗證呢?這樣你可能會想,我再去寫幾個函數去驗證。但是你可能發現,這樣的函數很難維護,而且可用性不高,擴展性也比較差,復用性就更談不上了。
這就是今天要談的[Guava](http://www.iteblog.com/archives/tag/guava "查看 Guava 中的全部文章")中提供的[Preconditions](http://www.iteblog.com/archives/tag/preconditions "查看 Preconditions 中的全部文章")類,[Preconditions](http://www.iteblog.com/archives/tag/preconditions "查看 Preconditions 中的全部文章")提供了大量的用于參數的檢測函數,在項目中使用了這個類,不僅可以簡化我們的代碼,而且可讀性大大提高,何樂而不為呢?強烈建議在您的代碼中使用這個類,而且在[Preconditions](http://www.iteblog.com/archives/tag/preconditions "查看 Preconditions 中的全部文章")類中的所有函數都是static修飾的,這意味著你不需要聲明(你不可以申請一個Preconditions對象,因為Preconditions的構造函數用private修飾的)一個Preconditions類對象,而可以直接使用這個類提供的方法。在Preconditions中提供的校驗類主要有以下幾個:
1、static void checkArgument(boolean expression):這個函數在expression為true的時候將不會發生任何事情,如果expression為false將會拋出IllegalArgumentException異常,說明輸入的參數非法;[Guava](http://www.iteblog.com/archives/tag/guava "查看 Guava 中的全部文章")中的實現如下:
~~~
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
~~~
2、static void checkArgument(boolean expression, Object errorMessage):這個函數和上面的類似,只不過在拋出異常的同時多數出了errorMessage提示信息;Guava中的實現如下:
~~~
public static void checkArgument(
boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
~~~
3、static void checkArgument(boolean expression, String errorMessageTemplate, Object… errorMessageArgs):和上面的類似,只不過輸出的提示信息可以被格式化成一定的格式;Guava中的實現如下:
~~~
public static void checkArgument(boolean expression,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(
format(errorMessageTemplate, errorMessageArgs));
}
}
~~~
4、static int checkElementIndex(int index, int size)檢查index是否為在一個長度為size的list、string或array合法的范圍。 index的范圍區間是[0, size)(包含0不包含size)。無需直接傳入list、string或array, 只需傳入大小。返回index。失敗時拋出的異常類型:IndexOutOfBoundsException;Guava中的實現如下:
~~~
public static int checkElementIndex(int index, int size) {
return checkElementIndex(index, size, "index");
}
~~~
5、static int checkElementIndex(int index, int size, String desc)和上面的類似,只不過在出現異常的時候多數出一些提示信息(desc);Guava中的實現如下:
~~~
public static int checkElementIndex(
int index, int size, @Nullable String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException(badElementIndex(index, size, desc));
}
return index;
}
~~~
6、static T checkNotNull(T reference)檢查reference不為null時,則直接返回value;否則拋出的異常類NullPointerException;Guava中的實現如下:
~~~
public static T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
~~~
7、static T checkNotNull(T reference, Object errorMessage)和上面的功能一樣,只不過在拋出異常的時候輸出了一些提示信息;Guava中的實現如下:
~~~
public static T checkNotNull(T reference, @Nullable Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
~~~
8、static T checkNotNull(T reference, String errorMessageTemplate, Object… errorMessageArgs)和上面的類是,但是在出現異常的時候輸出了格式化的錯誤信息提示;Guava中的實現如下:
~~~
public static T checkNotNull(T reference,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (reference == null) {
// If either of these parameters is null, the right thing happens anyway
throw new NullPointerException(
format(errorMessageTemplate, errorMessageArgs));
}
return reference;
}
~~~
9、static int checkPositionIndex(int index, int size)檢查位置index是否為在一個長度為size的list、string或array合法的范圍。 index的范圍區間是[0, size)(包含0不包含size)。無需直接傳入list、string或array, 只需傳入大小。成功的時候返回index;失敗時拋出的異常類型:IndexOutOfBoundsException;Guava中的實現如下:
~~~
public static int checkPositionIndex(int index, int size) {
return checkPositionIndex(index, size, "index");
}
~~~
10、static int checkPositionIndex(int index, int size, String desc)和上面的功能一樣,在失敗的時候返回提示信息(desc);Guava中的實現如下:
~~~
public static int checkPositionIndex(
int index, int size, @Nullable String desc) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc));
}
return index;
}
~~~
11、static void checkPositionIndexes(int start, int end, int size)檢查[start, end)是一個長度為size的list、string或array合法的范圍子集。失敗時拋出的異常類型:IndexOutOfBoundsException;Guava中的實現如下:
~~~
public static void checkPositionIndexes(int start, int end, int size) {
// Carefully optimized for execution by hotspot (explanatory comment above)
if (start < 0 || end < start || end > size) {
throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size));
}
}
~~~
12、static void checkState(boolean expression)這個判斷expression是否為true,如果是則什么都不做,否則拋出IllegalStateException異常;Guava中的實現如下:
~~~
public static void checkState(boolean expression) {
if (!expression) {
throw new IllegalStateException();
}
}
~~~
13、static void checkState(boolean expression, Object errorMessage)和上面的功能一樣,只不過在拋出異常的時候輸出了一些提示信息;Guava中的實現如下:
~~~
public static void checkState(
boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
~~~
14、static void checkState(boolean expression, String errorMessageTemplate, Object… errorMessageArgs)和上面的類是,但是在出現異常的時候輸出了格式化的錯誤信息提示;Guava中的實現如下:
~~~
public static void checkState(boolean expression,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (!expression) {
throw new IllegalStateException(
format(errorMessageTemplate, errorMessageArgs));
}
}
~~~
說了這么多,如何來用這個類呢?如下所示:
~~~
import com.google.common.base.Preconditions;
public void TestPre(Person person, List plist, int index) {
Preconditions.checkArgument(person != null);
Preconditions.checkNotNull(plist);
Preconditions.checkState(index > 0);
Preconditions.checkPositionIndex(index, plist.size());
Preconditions.checkElementIndex(index, plist.size());
}
~~~
這樣就可以測試一個函數輸入的參數是否合法。在Guava中的Strings類中還有Strings.isNullOrEmpty(“”)和Strings.emptyToNull(“”);兩個用于檢測字符串參數是否合法的函數,使用起來和Preconditions差不多,很簡單,具體的就不介紹了。
Guava中的Preconditions有以下幾個優點:(1)、在靜態導入后, 方法很明確無歧義, checkNotNull可以清楚地告訴你它是干什么的, 它會拋出怎樣的異常。(2、)簡單而又強大的可變參數’printf’風格的自定義錯誤信息。也去你代碼中加入Preconditions類吧!
(完)
轉載請注明: 轉載自[過往記憶(http://www.iteblog.com/)](http://www.iteblog.com/)
本文鏈接地址:?[Guava學習之Preconditions(http://www.iteblog.com/archives/570)](http://www.iteblog.com/archives/570)