Spring的Assert工具类的用法【转载】

转载自[url]http://blog.csdn.net/StayHungry2016/article/details/54574526[/url]
Assert断言工具类,通常用于数据合法性检查,在JAVA编程中,通常会编写如下代码:
if (name == null || name.equls("")) {
逻辑处理
}
在所有方法中都使用手工检测合法性的方式并不是太好,因为这样影响了代码的可读性,
[b]若使用Assert工具类上面的代码可以简化为:
Assert.hasText((name, "参数错误!"); [/b]
这样可以大大增强代码的可读性,介绍一下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的工具类(import org.springframework.util.Assert)
   留下个API地址,需要的自己去查阅API   [url]http://www.apihome.cn/api/spring/Assert.html[/url]
Assert类具体实现部分:
/**
* @deprecated as of 4.3.7, in favor of {@link #doesNotContain(String, String, String)}
*/
@Deprecated
public static void doesNotContain(String textToSearch, String substring) {
doesNotContain(textToSearch, substring,
"[Assertion failed] - this String argument must not contain the substring [" + substring + "]");
}

/**
* Assert that an array contains elements; that is, it must not be
* {@code null} and must contain at least one element.
* <pre class="code">Assert.notEmpty(array, "The array must contain elements");</pre>
* @param array the array to check
* @param message the exception message to use if the assertion fails
* @throws IllegalArgumentException if the object array is {@code null} or contains no elements
*/
public static void notEmpty(Object[] array, String message) {
if (ObjectUtils.isEmpty(array)) {
throw new IllegalArgumentException(message);
}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值