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
相关推荐
木易小熙6 天前
Guava Cache
java·spring·guava
Full Stack Developme6 天前
Java 工具类 Hutool、Guava 与 Apache Commons 的区别
java·apache·guava
Mr.456713 天前
【干货分享】Guava LoadingCache 使用指南:打造高性能本地缓存
guava
sibylyue1 个月前
Guava中常用的工具类
java·guava
howeres3 个月前
Guava
guava
sqyaa.3 个月前
Guava LoadingCache
jvm·缓存·guava
杨某一辰3 个月前
【Guava】1.0.设计虚拟机的方向
guava
赶路人儿3 个月前
guava限流器RateLimiter源码详解
guava
MonkeyKing_sunyuhua3 个月前
Guava Cache 本地项目缓存
缓存·guava
杨某一辰4 个月前
【Guava】0.做自己的编程语言
c++·guava·语言设计