Assert常用断言
notNull(Object object, "object is required")
- 对象非空
isTrue(Object object, "object must be true")
- 对象必须为true
notEmpty(Collection collection, "collection must not be empty")
- 集合非空
hasLength(String text, "text must be specified")
- 字符不为null且字符长度不为0
hasText(String text, "text must not be empty")
- text 不为null且必须至少包含一个非空格的字符
isInstanceOf(Class clazz, Object obj, "clazz must be of type [clazz]")
- obj必须能被正确造型成为clazz 指定的类
demo
code
package demo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
public class AssertDemo {
public static void main(String... args) {
String name = new String();
// traditional
if (null == name || "".equals(name)) {
// throw error message
}
// StringUtils
if (StringUtils.isBlank(name)) {
// throw error message
}
// Assert
Assert.hasText(name, "error message");
System.out.println("name:" + name);
}
}
result
总结
1、Assert对入参进行检查,如果不满足条件,抛出异常IllegalArgumentException;
2、使用Assert可以简化方法入参检测的代码,并且Assert不依赖Spring容器,可以在自己的应用中使用这个工具类。