1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| @Slf4j public class EnumValidator implements ConstraintValidator<EnumValid, String> {
private Class<? extends Enum<?>> enumClass;
@Override public void initialize(EnumValid enumValid) { enumClass = enumValid.enumClass(); }
@Override public boolean isValid(String value, ConstraintValidatorContext context) { if (!valid(value)) { throw new RuntimeException("invalid input parameter."); return false; } return true; }
private boolean valid(String value) { try { if (enumClass.isEnum()) {
Method method = enumClass.getMethod("isValidName", value.getClass()); Boolean result = (Boolean)method.invoke(null, value); return result != null && result; } } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) { throw new RuntimeException("Enum values valid error."); } return false; }
}
|