java 多参数校验工具类

java 校验多个参数工具类
1、定义注解

package com.shaoyu.utilscore.Response_zy.paramsCheck;

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

/**
 * @author shaoyu
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface paramsValid {
    // 字段名
    String fieldName();

    // 是否为空
    boolean required() default false;

    // 长度
    int len() default 0;

    // 正则
    String regular() default  "";
}

2 编写工具类

package com.shaoyu.utilscore.Response_zy.paramsCheck;

import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class paramsUtil {
    @FunctionalInterface
    public interface ValidComsumer<T> {
        void sonsume(T obj , List<String> result);
    }

    public static <T> boolean valid(List<T> list,ValidComsumer<T> comsumer) throws Exception{
        if (list.size() <= 0) {
            return false;
        }
        Class<?> aClass = list.get(0).getClass();
        List<Field> fields = new ArrayList<>();
        getFields(aClass,fields);

        // 过滤待验证的字段
        List<Field> preValidList = fields.stream().filter(each -> each.getAnnotation(paramsValid.class) != null).collect(Collectors.toList());
        Map<String, String> collect = preValidList
                .stream()
                .collect(Collectors.toMap(Field::getName, item -> item.getAnnotation(paramsValid.class).fieldName()));
        List<Field> require = preValidList.stream().filter(each -> each.getAnnotation(paramsValid.class).required()).collect(Collectors.toList());
        List<Field> len = preValidList.stream().filter(each -> each.getAnnotation(paramsValid.class).len()!=0).collect(Collectors.toList());
        List<Field> regular = preValidList.stream()
                .filter(each ->
                        (!StringUtils.isEmpty(each.getAnnotation(paramsValid.class).regular()))).collect(Collectors.toList());

        // 开始校验
        List<String> result = new ArrayList<>();
        // 1空值校验
        for (Field each:require) {
            // 设置访问权限
            each.setAccessible(true);
            Object value = each.get(list.get(0));
            if (null == value) {
                result.add(collect.get(each.getName())+"不能为空!");
            }else {
                if (value instanceof String && StringUtils.isEmpty(value)) {
                    result.add(collect.get(each.getName())+"不能为空!");
                }
            }

        }
        if (result.size() > 0) {
            // 执行回调函数
            comsumer.sonsume(list.get(0) , result);
            return false;
        }
        // 长度校验
        for (Field each:len) {
            // 设置访问权限
            each.setAccessible(true);
            Object value = each.get(list.get(0));
            if (value instanceof String) {
                if (value.toString().length() > each.getAnnotation(paramsValid.class).len()) {
                    result.add(collect.get(each.getName())+"长度不能超过"+each.getAnnotation(paramsValid.class).len());
                }
            }
        }
        if (result.size() > 0) {
            // 执行回调函数
            comsumer.sonsume(list.get(0) , result);
            return false;
        }
        // 正则校验
        for (Field each:regular) {
            // 设置访问权限
            each.setAccessible(true);
            Object value = each.get(list.get(0));
            if (value instanceof String) {
                // 匹配规则
                String rex = each.getAnnotation(paramsValid.class).regular();
                boolean matches = value.toString().matches(rex);
                if (!matches) {
                    result.add(collect.get(each.getName())+"格式错误!");
                }
            }
        }
        if (result.size() > 0) {
            // 执行回调函数
            comsumer.sonsume(list.get(0) , result);
            return false;
        }
        return true;
    }

    private static void getFields(Class<?> aClass,List<Field> fields) {
        // 获取子类字段
        Field[] declaredFields = aClass.getDeclaredFields();
        fields.addAll(Arrays.asList(declaredFields));
        // 取父类字段
        if (!aClass.getSuperclass().equals(Object.class)){
            getFields(aClass.getSuperclass(),fields);
        }
    }
}

3、使用步骤
①需要校验的类字段上添加注解
如电话类tel中的phone字段:

@paramsValid(fieldName = "电话号码",required = true,len = 11,regular = "^1[3|4|5|7|8][0-9]{9}$")`
private String phone;

②掉用

 List<tel> t = new ArrayList<>();
paramsUtil.valid(t,(item, res)->{throw new Exception(res.toString());});
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

少宇的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值