Spring Assert工具类的用法
2015-09-17 14:34
441 查看
Spring在提供一个强大的应用开发框架的同时也提供了很多优秀的开发工具类,合理的运用这些工具,将有助于提高开发效率、增强代码质量。下面就最常用的Assert工具类,简要介绍一下它的用法。
Assert断言工具类,通常用于数据合法性检查,在JAVA编程中,通常会编写如下代码:
if (name == null || name.equls("")) {
throw new IllegalArgumentException("参数错误!");
}
在所有方法中都使用手工检测合法性的方式并不是太好,因为这样影响了代码的可读性,若使用Assert工具类上面的代码可以简化为:
Assert.hasText((name, "参数错误!");
这样可以大大增强代码的可读性,下面我们来介绍一下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 指定的类
Assert断言工具类,通常用于数据合法性检查,在JAVA编程中,通常会编写如下代码:
if (name == null || name.equls("")) {
throw new IllegalArgumentException("参数错误!");
}
在所有方法中都使用手工检测合法性的方式并不是太好,因为这样影响了代码的可读性,若使用Assert工具类上面的代码可以简化为:
Assert.hasText((name, "参数错误!");
这样可以大大增强代码的可读性,下面我们来介绍一下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 指定的类
相关文章推荐
- JAVA解析JSON
- eclipse编译Syntax error, parameterized types are only available if source level is 5.0
- Java 脚本支持
- eclipse安卓开发环境搭建全过程
- struts2中<s:property>的用法
- Spring AOP Advices - After throwing advice example - xml based configuration
- 韩顺平 java 第二讲 变量 数据类型
- test3.11
- java日志: logback和slf4j
- spark取得lzo压缩文件报错 java.lang.ClassNotFoundException
- Spring AOP Advices - After returning advice example - xml based configuration
- 使用CXF框架学习搭建WebService(三)
- 通过Java Api与HBase交互(转)
- Spring Resource bundle with ResourceBundleMessageSource example
- JavaBean的get、set方法引发的讨论
- HBase Java API类介绍
- Java中的StringUtils类
- test3.10
- Java在Jar包中初始化log4j的方法
- MyEclipse快捷键大全(Java程序员专供)