天天看點

Spring斷言工具類 “Assert” 的基本操作!

斷言的概念

在程式設計中,斷言是一種放在程式中的一階邏輯,目的是為了标示與驗證程式開發者預期的結果-當程式運作到斷言的位置時,對應的斷言應該為真。若斷言不為真時,程式會中止運作,并給出錯誤消息。

Assert工具類

Spring的Assert斷言工具類,通常用于資料合法性檢查。位于

org.springframework.util.Assert

包下,使用Assert可以使複雜的判斷變得更加簡單。

常用方法

方法名(參數清單) 作用
Assert.notNull(Object object, “object is required”) 對象非空
Assert.isTrue(Object object, “object must be true”) 對象必須為true
Assert.notEmpty(Collection collection, “collection must not be empty”) 集合非空
Assert.hasLength(String text, “text must be specified”) 字元不為null且字元長度不為0
Assert.hasText(String text, “text must not be empty”) text 不為null且必須至少包含一個非空格的字元
Assert.isInstanceOf(Class clazz, Object obj, “clazz must be of type [clazz]”) obj必須能被正确轉型成為 clazz 指定的類

案例

  • 平時做判斷通常都是這樣寫
if (message== null || message.equls("")) {  
    throw new IllegalArgumentException("輸入資訊錯誤!");  
} 
           
  • 用Assert工具類上面的代碼可以簡化為

文章到此就結束了,其它方法同學們可以私下自行進行測試。

Spring斷言工具類 “Assert” 的基本操作!