Guava中Preconditions校验

Guava中Preconditions校验

    • 场景引入
    • [Guava 参数校验 Preconditions](#Guava 参数校验 Preconditions)

场景引入

提出疑问?为什么不直接使用 jsr330校验注解对实体类进行校验呢?

答:不同的场景,如短信码验证登录,账号密码登录此类的实体,对于字段是否必填并不是必须的。

java 复制代码
@Data
class UserLoginDTO {
    // @NotBlank(message = "手机号不能为空")
    private String phone;

    // @NotBlank(message = "验证码不能为空")
    private String code;
    
    // @NotBlank(message = "密码不能为空")
    private String password;
}

应对这样的dto实体,只能在业务中进行判空处理,如下面的操作:

java 复制代码
if (StringUtils.isBlank(userLoginDTO.getPhone())) {
    // ...
}
if (StringUtils.isBlank(userLoginDTO.getCode())) {
    // ...
}
if (StringUtils.isBlank(userLoginDTO.getPassword())) {
    // ...
}

如果输入参数少的时候,还好,如果很多就会变成大量的if(判空操作),很不优雅...

此时就可以使用 guava 的 Preconditions来完成上面的判空操作了,如:

java 复制代码
Preconditions.checkArgument(StringUtils.isNotBlank(userLoginDTO.getPhone()), "手机号不能为空");
Preconditions.checkArgument(StringUtils.isNotBlank(userLoginDTO.getCode()), "验证码不能为空");
Preconditions.checkArgument(StringUtils.isNotBlank(userLoginDTO.getPassword()), "密码不能为空");

Guava 参数校验 Preconditions

pom 依赖引入

xml 复制代码
<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>版本号</version>
</dependency

常用的方法

简单的列举Guava中Preconditions类的一些常用校验方法:

方法名 描述 抛出异常
checkArgument(boolean expression, String errorMessageTemplate, Object... errorMessageArgs) 校验方法参数。如果expressionfalse,则抛出IllegalArgumentException IllegalArgumentException
checkNotNull(T reference) 校验reference不为null。如果为null,则抛出NullPointerException NullPointerException
checkNotNull(T reference, String errorMessage) 类似于checkNotNull(T reference),但允许提供一个错误消息 NullPointerException
checkState(boolean expression) 校验程序状态。如果expressionfalse,则抛出IllegalStateException IllegalStateException
checkState(boolean expression, String errorMessageTemplate, Object... errorMessageArgs) 类似于checkArgument,但抛出的是IllegalStateException IllegalStateException
checkElementIndex(int index, int size, String desc) 校验索引是否有效(大于等于0且小于size)。如果无效,则抛出IndexOutOfBoundsException IndexOutOfBoundsException
checkPositionIndex(int index, int size, String desc) 类似于checkElementIndex,但允许索引等于size IndexOutOfBoundsException
checkPositionIndexes(int start, int end, int size, String desc) 校验起始和结束索引是否有效,用于表示子序列范围 IndexOutOfBoundsException
相关推荐
我是鸹貔13 天前
guava-Immutable(不可变集合)
java·guava
sco528215 天前
SpringBoot 整合 Guava Cache 实现本地缓存
缓存·oracle·guava
qq_3660862217 天前
guava中对Map的扩展数据结构
spring boot·guava
xidianhuihui19 天前
Guava Cache实现原理及最佳实践
java·spring·guava
落魄程序员在线炒饼23 天前
springboot集成guava布隆过滤器
spring boot·后端·guava
面试鸭1 个月前
什么是令牌桶算法?工作原理是什么?使用它有哪些优点和注意事项?
java·开发语言·学习·guava
进击的小白菜2 个月前
Sprong Boot学习|使用 guava-retrying 实现重试
spring boot·学习·guava
被风吹过的会不会要逝去2 个月前
Guava LocalCache源码分析:LocalCache生成
java·spring·guava
weixin_437398212 个月前
Google Guava Cache简介
java·spring·guava