1. 程式人生 > >Accert 類中的斷言方法,

Accert 類中的斷言方法,

1. notNull(Object object)  
  當 object 不為 null 時丟擲異常,notNull(Object object, String message) 方法允許您通過 message 定製異常資訊。和 notNull() 方法斷言規則相反的方法是 isNull(Object object)/isNull(Object object, String message),它要求入參一定是 null;

2. isTrue(boolean expression) / isTrue(boolean expression, String message)  
  當 expression 不為 true 丟擲異常; 

3. notEmpty(Collection collection) / notEmpty(Collection collection, String message) 
  當集合未包含元素時丟擲異常。 
  notEmpty(Map map) / notEmpty(Map map, String message) 和 notEmpty(Object[] array, String message) / notEmpty(Object[] array, String message) 分別對 Map 和 Object[] 型別的入參進行判斷;

4. hasLength(String text) / hasLength(String text, String message)  
  當 text 為 null 或長度為 0 時丟擲異常;

5. hasText(String text) / hasText(String text, String message)  
  text 不能為 null 且必須至少包含一個非空格的字元,否則丟擲異常;

6. isInstanceOf(Class clazz, Object obj) / isInstanceOf(Class type, Object obj, String message)  
  如果 obj 不能被正確造型為 clazz 指定的類將丟擲異常;

7. isAssignable(Class superType, Class subType) / isAssignable(Class superType, Class subType, String message)  
  subType 必須可以按型別匹配於 superType,否則將丟擲異常;

  使用 Assert 斷言類可以簡化方法入參檢測的程式碼,如 InputStream getData(String file) 在應用 Assert 斷言類後,其程式碼可以簡化為以下的形式:

public InputStream getData(String file){ 
    Assert.hasText(file,"file入參不是有效的檔案地址"); 
    ① 使用 Spring 斷言類進行方法入參檢測 
… 
}