轉載自[url]http://blog.csdn.net/StayHungry2016/article/details/54574526[/url]
Assert斷言工具類,通常用于資料合法性檢查,在JAVA程式設計中,通常會編寫如下代碼:
if (name == null || name.equls("")) {
邏輯處理
}
在所有方法中都使用手工檢測合法性的方式并不是太好,因為這樣影響了代碼的可讀性,
[b]若使用Assert工具類上面的代碼可以簡化為:
Assert.hasText((name, "參數錯誤!"); [/b]
這樣可以大大增強代碼的可讀性,介紹一下Assert 類中的常用斷言方法:
notNull(Object object, "object is required") - 對象非空 3hf
isTrue(Object object, "object must be true") - 對象必須為true
notEmpty(Collection collection, "collection must not be empty") - 集合非空
hasLength(String text, "text must be specified") - 字元不為null且字元長度不為0
hasText(String text, "text must not be empty") - text 不為null且必須至少包含一個非空格的字元
isInstanceOf(Class clazz, Object obj, "clazz must be of type [clazz]") - obj必須能被正确造型成為clazz 指定的類
隻記錄這麼多,具體自己去找spring的工具類(import org.springframework.util.Assert)
留下個API位址,需要的自己去查閱API [url]http://www.apihome.cn/api/spring/Assert.html[/url]
Assert類具體實作部分:
/**
* @deprecated as of 4.3.7, in favor of {@link #doesNotContain(String, String, String)}
*/
@Deprecated
public static void doesNotContain(String textToSearch, String substring) {
doesNotContain(textToSearch, substring,
"[Assertion failed] - this String argument must not contain the substring [" + substring + "]");
}
/**
* Assert that an array contains elements; that is, it must not be
* {@code null} and must contain at least one element.
* <pre class="code">Assert.notEmpty(array, "The array must contain elements");</pre>
* @param array the array to check
* @param message the exception message to use if the assertion fails
* @throws IllegalArgumentException if the object array is {@code null} or contains no elements
*/
public static void notEmpty(Object[] array, String message) {
if (ObjectUtils.isEmpty(array)) {
throw new IllegalArgumentException(message);
}
}