Assert翻譯爲中文爲"斷言",就是斷定某一個實際的值就爲自己預期想得到的,如果不一樣就拋出異常。
測試代碼或者調試程序時,總會做出一些假設,斷言就是用於在代碼中捕捉這些假設。當要判斷一個方法傳入的參數時,我們就可以使用斷言。
1. notNull(Object object)
當 object 不爲 null 時拋出異常,notNull(Object object, String message) 方法允許您通過 message 定製異常信息。和 notNull() 方法斷言規則相反的方法是 isNull(Object object)/isNull(Object object, String message),它要求入參一定是 null;
spring源碼,如下:
/**
* Assert that an object is not <code>null</code> .
* <pre class="code">Assert.notNull(clazz, "The class must not be null");</pre>
* @param object the object to check
* @param message the exception message to use if the assertion fails
* @throws IllegalArgumentException if the object is <code>null</code>
*/
public static void notNull(Object object, String message) {
if (object == null) {
throw new IllegalArgumentException(message);
}
}
該函數的意思是傳入的object必須不能爲空。如果爲空就拋出異常。
2. isTrue(boolean expression) / isTrue(boolean expression, String message)
當 expression 不爲 true 拋出異常;
Assert.IsTrue方法:
Assert.IsTrue(jsonData.IsArray);
Assert.IsTrue(jsonData.IsArray,“its not a array”);
例如:
public Order create(Cart cart, Receiver receiver, PaymentMethod paymentMethod, ShippingMethod shippingMethod,
BoxMethod boxMethod, CouponCode couponCode, boolean isInvoice) {
Assert.notNull(cart);
Assert.notEmpty(cart.getCartItems());
Assert.isTrue(cart.checkedSize()>0, "購物項選擇必須大於0");
Assert.notNull(receiver);
Assert.notNull(paymentMethod);
Assert.notNull(shippingMethod);
}這樣可以檢測傳入的參數是否符合要求,當這些斷言方法在入參不滿足要求時就會拋出 IllegalArgumentException。
斷言常用的方法
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,否則將拋出異常;