package cn.fw.rp.annotation; 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 Devin * @date: 2018/4/18 20:44 */ @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = EnumValid.Validator.class) public @interface EnumValid { String message() default "枚举类型不符合"; Class[] groups() default {}; Class[] payload() default {}; Class> enumClass(); String enumMethod(); class Validator implements ConstraintValidator { private Class> enumClass; private String enumMethod; @Override public void initialize(EnumValid enumValid) { enumMethod = enumValid.enumMethod(); enumClass = enumValid.enumClass(); } @Override public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) { if (value == null) { return Boolean.FALSE; } if (enumClass == null || enumMethod == null) { return Boolean.FALSE; } Class valueClass = value.getClass(); try { Method method = enumClass.getMethod(enumMethod, valueClass); if (!Boolean.TYPE.equals(method.getReturnType()) && !Boolean.class.equals(method.getReturnType())) { throw new RuntimeException(String.format("%s method return is not boolean type in the %s class", enumMethod, enumClass)); } if (!Modifier.isStatic(method.getModifiers())) { throw new RuntimeException(String.format("%s method is not static method in the %s class", enumMethod, enumClass)); } Boolean result = (Boolean) method.invoke(null, value); return result == null ? false : result; } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException | SecurityException e) { throw new RuntimeException(String.format("This %s(%s) method does not exist in the %s", enumMethod, valueClass, enumClass), e); } } } }