在java中的Assert是使用的 package org.springframework.util; 這個包中的Assert類, 這個類的方法,能夠用於一些校驗,若是失敗就拋出異常,並能夠編輯異常的信息。java
經常使用的方法有spring
//若是表達式爲false,則拋出異常 public static void isTrue(boolean expression, String message) { if (!expression) { throw new IllegalArgumentException(message); } }
還能夠驗證是否爲空express
//若是對象不爲空就拋出異常 public static void isNull(Object object, String message) { if (object != null) { throw new IllegalArgumentException(message); } } //對象爲空時拋出異常 public static void notNull(Object object, String message) { if (object == null) { throw new IllegalArgumentException(message); } } //判斷集合類是否爲空,若是爲空則拋出異常,使用的是CollectionUtils的方法 public static void notEmpty(Collection<?> collection, String message) { if (CollectionUtils.isEmpty(collection)) { throw new IllegalArgumentException(message); } }
判斷對象是都爲某個類型code
//若是obj對象不爲type類型,則拋出異常 public static void isInstanceOf(Class<?> type, Object obj, String message) { notNull(type, "Type to check against must not be null"); if (!type.isInstance(obj)) { instanceCheckFailed(type, obj, message); } }