Spring的Assert工具類的用法
Spring在提供一個強大的應用開發框架的同時也提供了很多優秀的開發工具類,合理的運用這些工具,將有助於提高開發效率、增強代碼質量。下面就最常用的Assert工具類,簡要介紹一下它的用法。
Assert斷言工具類,通常用於數據合法性檢查,在JAVA編程中,通常會編寫如下代碼:
if (name == null || name.equls("")) {
throw new IllegalArgumentException("參數錯誤!");
}
在所有方法中都使用手工檢測合法性的方式並不是太好,因爲這樣影響了代碼的可讀性,若使用Assert工具類上面的代碼可以簡化爲:
Assert.hasText((name, "參數錯誤!");
這樣可以大大增強代碼的可讀性,下面我們來介紹一下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 指定的類