Search code examples
javaenumsannotations

Java Spring Boot custom validation: generic validation for all enums


For a SpringBoot project I'm using custom validation using custom annotations. In particular, I have a lot of enums and I would like to validate if into the inputs there are correct enums values (e.g. from json to DTO objects)

I'm using this approach: I defined my annotation:

@Target( { FIELD, PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = PlatformValidator.class)
public @interface PlatformValidation {

    String message() default "Invalid platform format";

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

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

and my validator:

public class PlatformValidator implements ConstraintValidator<PlatformValidation, String>
{
    public boolean isValid(String platform, ConstraintValidatorContext cxt) {

        try {
            if (!isNull(platform)) {
                Platform.valueOf(platform);
            }
            return true;
        } catch (Exception ex) {
            return false;
        }
    }
}

My question is, can I have a generic enum validation annotation and specify the enum that I need as a parameter of my annotation?

Something like @MyValidation(enum=MyEnum, message= ...)


Solution

  • For the generics approach is use Java reflection. So the annotation should be:

    @EnumValidation(enum=YourEnum.class, message=...)
    

    The tutorial about reflection: Jenkov's Tutorial