Spring下的断言工具类 Assert 和Java中断言关键子assert

Spring下的断言工具类 org.springframework.util.Assert;

断言工具类可以用来校验参数是否合法,替代if判断

1 //替换前
2 if (a == null) {
3     throw new IllegalArgumentException("参数输入有误");
4 }
5 //替换后
6 Assert.notNull(a,"参数输入有误");

常用断言方法

1 Assert.notNull(Object object, "object is required")    -    对象非空 
2 Assert.isTrue(Object object, "object must be true")   -    对象必须为true   
3 Assert.notEmpty(Collection collection, "collection must not be empty")    -    集合非空  
4 Assert.hasLength(String text, "text must be specified")   -    字符不为null且字符长度不为0   
5 Assert.hasText(String text, "text must not be empty")    -     text 不为null且必须至少包含一个非空格的字符  
6 Assert.isInstanceOf(Class clazz, Object obj, "clazz must be of type [clazz]")    -    obj必须能被正确造型成为clazz 指定的类
 
Java中的断言关键字 assert
assert关键字对一个boolean表达式进行检查,若检查结果为true,表示程序无异常继续执行,若检查结果false,说明程序已经处于不正确的状态下,系统将给出警告并且退出。
 
assert 语法
assert [boolean expression]
如果[boolean表达式]为true,则程序继续执行。
如果为false,则程序抛出AssertionError,并终止执行。
 
assert [boolean expression] : [error expression]
如果[boolean expression]为true,则程序继续执行。
如果为false,则程序抛出java.lang.AssertionError,输出[error expression]。
 
在ideal中默认没有开启-ea断言检查功能,因此使用断言进行测试时需要手动修改配置
ideal中开启断言
 

猜你喜欢

转载自www.cnblogs.com/herberts/p/10865221.html