码迷,mamicode.com
首页 > 编程语言 > 详细

Spring的Assert工具类的用法

时间:2018-01-19 15:49:47      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:ring   cep   分享图片   java   cti   方式   note   ima   png   

简介

今天在看spring mvc源码时看到下面代码,感觉蛮有意思的,在这里记录下

技术分享图片

Assert断言工具类,通常用于数据合法性检查,在JAVA编程中,通常会编写如下代码:  

if (name == null || name.equls("")) {  
    throw new IllegalArgumentException("参数错误!");  
}   
     
在所有方法中都使用手工检测合法性的方式并不是太好,因为这样影响了代码的可读性,若使用Assert工具类上面的代码可以简化为:  
Assert.hasText((name, "参数错误!");

这样可以大大增强代码的可读性,下面我们来介绍一下Assert 类中的常用断言方法:  
notNull(Object object, "object is required")    -    对象非空 3hf  
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 指定的类

Spring的Assert工具类的用法

标签:ring   cep   分享图片   java   cti   方式   note   ima   png   

原文地址:https://www.cnblogs.com/520playboy/p/8316872.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!