JAVA手写通过注解验证范围合规的值


@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IsNull {
    String Message();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NumRange {
    int Min();
    int Max();
    String Message();
}
public class MyValidationUtil {
    private static <T> List<String> Validate(T obj){
        ArrayList<String> warning = new ArrayList<>();
        Class clazz = obj.getClass();
        //获取类的所有属性
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            //获取属性 declaredField.getName() 属性名
            Field field = null;
            try {
                field = clazz.getDeclaredField(declaredField.getName());
                field.setAccessible(true);
                Annotation[] annotations = field.getAnnotations();
                for (Annotation annotation : annotations) {
                    if (annotation instanceof IsNull) {
                        Object o = field.get(obj);
                        IsNull isNull = (IsNull) annotation;
                        if (o == null) {
                            warning.add(isNull.Message());
                        }
                    }
                    if (annotation instanceof NumRange) {
                        Object o = field.get(obj);
                        if (o instanceof Integer) {
                            int value = (Integer) o;
                            NumRange numRange = (NumRange) annotation;
                            //获取注解的属性值
                            if (!(value < numRange.Max() && value > numRange.Min())) {
                                warning.add("错误" + numRange.Message());
                            }
                        }
                    }
                }
            } catch (NoSuchFieldException | IllegalAccessException ignored) {
            }

        }
        return warning;
    }
}
    @NumRange(Min = 2,Max=99,Message="vipid为9-99")
    private Integer vipId;
    @IsNull(Message = "sex不能空")
    private Integer sex;
    @IsNull(Message = "名字不能空")
    private String vipName;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值