自定义注解校验枚举参数

自定义注解

package com.learn.annotations;

import com.learn.exception.EnumValueCheckException;
import com.learn.exception.ExceptionCode;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * @author kermit.liu on 2018/3/18
 * @desc: 枚举校验
 */
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumValue.Validator.class)
public @interface EnumValue {

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 枚举类
     */
    Class<? extends Enum<?>> enumClass();

    /**
     * 枚举校验的方法
     */
    String enumMethod() default "isValidEnum";

    /**
     * 默认提示文字
     */
    String message() default "enum.value.invalid";

    boolean allowNull() default false;

    /**
     * 校验器
     */
    class Validator implements ConstraintValidator<EnumValue, Object> {

        private Class<? extends Enum<?>> enumClass;
        private String enumMethod;
        private boolean allowNull;

        @Override
        public void initialize(EnumValue enumValue) {
            enumMethod = enumValue.enumMethod();
            enumClass = enumValue.enumClass();
            allowNull = enumValue.allowNull();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            if (null == value) {
                return allowNull;
            }
            if (null == enumClass || null == enumMethod) {
                return Boolean.TRUE;
            }
            Class<?> valueClass = value.getClass();
            try {
                Method method = enumClass.getMethod(enumMethod, valueClass);
                if (!Boolean.TYPE.equals(method.getReturnType()) && !Boolean.class.equals(method.getReturnType())) {
                    throw new EnumValueCheckException(ExceptionCode.ENUM_CHECK_FAILURE,
                            String.valueOf(String.format("%s method return is not boolean type in the %s class", enumMethod, enumClass)));
                }
                if (!Modifier.isStatic(method.getModifiers())) {
                    throw new EnumValueCheckException(ExceptionCode.ENUM_CHECK_FAILURE,
                            String.valueOf(String.format("%s method is not static method in the %s class", enumMethod, enumClass)));
                }
                Boolean result = (Boolean) method.invoke(null, value);
                return result == null ? Boolean.FALSE : result;
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                throw new EnumValueCheckException(e);
            } catch (NoSuchMethodException | SecurityException e) {
                throw new EnumValueCheckException(ExceptionCode.ENUM_CHECK_FAILURE,
                        String.valueOf(String.format("This %s(%s) method does not exist in the %s", enumMethod, valueClass, enumClass)),
                        e);
            }
        }
    }
}

枚举?

package com.learn.common.enums;

/**
 * @author kermit.liu on 2018/3/15
 */
public enum MyEnum {

    /**
     *
     */
    WAREHOUSE("WAREHOUSE", "仓库"),
    HOTEL("HOTEL", "酒店"),
    SUPPLIER("SUPPLIER", "供应商");

    private String code;
    private String desc;

    MyEnum(String code, String desc) {
        this.code = code;
        this.desc = desc;
    }

    public String getCode() {
        return code;
    }

    public String getDesc() {
        return desc;
    }

    /**
     * 通过code生成枚举
     *
     * @param code code
     * @return MyEnum or null
     */
    public static MyEnum valueByCode(String code) {
        if (code == null) {
            return null;
        }
        for (MyEnum e : values()) {
            if (code.equals(e.code)) {
                return e;
            }
        }
        return null;
    }

    /**
     * 校验是否是该枚举
     *
     * @param code 枚举字符串
     * @return true or false
     */
    public static boolean isValidEnum(String code) {
        for (MyEnum myEnum : MyEnum.values()) {
            if (myEnum.getCode().equals(code)) {
                return true;
            }
        }
        return false;
    }
}

使用方法

@EnumValue(enumClass = MyEnum.class, enumMethod = "isValidEnum", allowNull = true, message = "tip message")
private String enumString;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值