使用注解统一校验参数非空

该博客介绍了如何使用注解和反射来创建一个工具类,实现对类中参数的统一非空校验。通过定义自定义注解和相应的校验方法,可以高效地检查待校验类的非空属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可修改做工具类

代码:

1. 待校验类:

public class User {

    @NonNull(content = "姓名不能为空", minLen = 2, maxLen = 100)
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2. 注解类

@Documented
@Target(value = ElementType.FIELD)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface NonNull {

    String name() default "";

    String content() default "";

    int maxLen() default 50;

    int minLen() default 1;
}

3. 校验

    public void test() {
        User user = new User();
        user.setName("老王");
        try {
            valid(user);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private <T> void valid(T user) throws IllegalAccessException, InvocationTargetException {
        Class<?> clazz = user.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        Method[] methods = clazz.getMethods();
        for (Field field : declaredFields) {
            validParams(user, methods, field);
        }
        System.out.println("==========参数校验通过=========");
    }

    private <T> void validParams(T user, Method[] methods, Field field) throws IllegalAccessException, InvocationTargetException {
        NonNull annotation = field.getAnnotation(NonNull.class);
        String fieldName;
        if (StringUtils.isNotBlank(annotation.name())) {
            fieldName = annotation.name();
        } else {
            fieldName = field.getName();
        }
        for (Method method : methods) {
            if (("get" + fieldName).toLowerCase().equals(method.getName().toLowerCase())) {
                Object getMethodResult = method.invoke(user, null);
                if (getMethodResult == null) {
                    System.out.println("==========非Null校验失败=========");
                    throw new IllegalArgumentException("[" + annotation.content() + "]为null");
                }
                if (getMethodResult instanceof String) {
                    if (StringUtils.isBlank(String.valueOf(getMethodResult))) {
                        System.out.println("==========非空校验失败=========");
                        throw new IllegalArgumentException("[" + annotation.content() + "]为空");
                    }
                    System.out.println(fieldName + "长度:" + String.valueOf(getMethodResult).length());
                    if (String.valueOf(getMethodResult).length() > annotation.maxLen()) {
                        System.out.println("==========长度超出指定范围=========");
                        throw new IllegalArgumentException("[" + fieldName + "]长度超出");
                    }
                    if (String.valueOf(getMethodResult).length() < annotation.minLen()) {
                        System.out.println("==========长度小于指定范围=========");
                        throw new IllegalArgumentException("[" + fieldName + "]长度不够");
                    }
                }
            }
        }
    }

结果参考:

name长度:2
==========参数校验通过=========
name长度:2
==========长度小于指定范围=========

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值