分享几个实用的参数校验注解(含字段依赖校验、枚举字段值有效性校验、参数类型转换)

本文分享了三种实用的参数校验注解,包括字段依赖校验,确保字段A值在特定情况下字段B不为空;枚举字段有效性校验,验证请求中的枚举字段值是否合法;以及String参数类型转换集成校验,针对Excel导入的日期和金额字段进行转换和校验。通过注解声明、处理类和应用示例,详细阐述了这些校验的实现方法。
摘要由CSDN通过智能技术生成

字段依赖校验相关代码

应用场景

某个字段的值校验依赖于另一个字段的值
举例:当字段A in {1,2,3}时,字段B不能为空

注解声明

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({
   ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNullWhen {
   

    //当前字段最小值
    long min() default 0;

    //依赖字段名
    String dependsOnField();

    //依赖字段值域
    String[] dependsOnFieldValues();

    //校验失败时的提示信息
    String message() default "";

}

注解处理类

public class ParamValidator {
   
	public static void validateWithDepends(Object validateObject) {
   
        List<Field> fieldList = new ArrayList<>();
        Collections.addAll(fieldList, validateObject.getClass().getDeclaredFields());
        Collections.addAll(fieldList, validateObject.getClass().getSuperclass().getDeclaredFields());
        for (Field field : fieldList) {
   
            NotNullWhen annotation = field.getDeclaredAnnotation(NotNullWhen.class);
            if (annotation == null) {
   
                continue;
            }
            Field dependsOnField = null;
            try {
   
                dependsOnField = validateObject.getClass().getDeclaredField(annotation.dependsOnField());
            } catch (NoSuchFieldException e) {
   
                e.printStackTrace();
                throw ServiceException.of(ResultCode.PARAM_INVALID);
            }
            try {
   
                dependsOnField.setAccessible(true);
                Object value = dependsOnField.get(validateObject);

                if (value == null) {
   
                    continue;
                }
                if (Arrays.stream(annotation.dependsOnFieldValues()).anyMatch(v -> String.valueOf(value).equals(v))) {
   
                    Object annotationFieldValue = null;
                    field.setAccessible(true);
                    annotationFieldValue = field.get(validateObject);
                    if (field.getType() == Integer.class || field.getType() == Long.class) {
   
                        if (annotationFieldValue == null || (Long.parseLong(String.valueOf(annotationFieldValue)) < annotation.min())) {
   
                            throw ServiceException.ofWarn(ResultCode.PARAM_INVALID, annotation.message());
                        }
                    }
                    if (field.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值