在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); } }