自定义注解校验枚举参数

自定义注解

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[] payload() default {};

    /**
     * 枚举类
     */
    Class> enumClass();

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

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

    boolean allowNull() default false;

    /**
     * 校验器
     */
    class Validator implements ConstraintValidator {

        private Class> 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;

 

你可能感兴趣的:(Spring,注解,枚举)