Java String validation using enum values and annotation

后端 未结 8 1517
暖寄归人
暖寄归人 2020-11-30 23:47

I want to validate a string against a set of values using annotations.

What I want is basically this:

@ValidateString(enumClass=com.co.enum)
String d         


        
8条回答
  •  被撕碎了的回忆
    2020-12-01 00:16

    I take up Rajeev Singla's response https://stackoverflow.com/a/21070806/8923905, just to optimize the code and allow the String parameter to be null, if in your application it is not mandatory and can be empty :

    1- Remove the @NotNull annotation on the Interface

    2- See the modified code below for the implementation.

    public class EnumValidatorImpl implements ConstraintValidator  {
    
        private List valueList = null;
    
        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            return null == value || valueList.contains(value.toUpperCase());
        }
    
        @Override
        public void initialize(EnumValidator constraintAnnotation) {
            valueList = new ArrayList<>();
            Class> enumClass = constraintAnnotation.enumClass();
    
            Enum[] enumValArr = enumClass.getEnumConstants();
    
            for(Enum enumVal : enumValArr) {
                valueList.add(enumVal.toString().toUpperCase());
            }
    
        }
    }
    

提交回复
热议问题