0

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= ...)

1
  • 1
    This should work fine (though you need a different name from enum and should probably just use Class<? extends Enum<?>> value()). Is there a specific reason you're not simply using the enum as the POJO property type? Commented Nov 4, 2022 at 18:41

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

How can I retrieve the parameter 'enum' (that it will be a .class) into my validator (into the isValid method) ?
@Safari you can retrieve by override method of initialize See more at here: baeldung.com/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.