I wrote a custom annotation in my project called CGC:
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = CGCValidator.class)
public @interface CGC {
    String message() default "{person.cgc.error}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    boolean canBeNull() default false;
    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @Documented
    public @interface List {
        CGC[] value();
    }
}
I have a validator class that uses the annotation and basically, as my first validation I wanna check if the field is null, but only If the annotation for that field has specified the "canBeNull" element as true (@CGC(canBeNull="true")). My question is: how can I access the canBeNull element inside my validator class?
*The validator should be something like this:
public class CGCValidator implements ConstraintValidator<CGC, String> {
    @Override
    public void initialize(CGC annotation) {
    }
    @Override
    public boolean isValid(String cgc, ConstraintValidatorContext constraintValidatorContext) {
    if(!canBeNull() && cgc == null) {
    return false;
    }
    ...
You can capture the canBeNull value in the initialize function:
class CGCValidator implements ConstraintValidator<CGC, String> {
    boolean canBeNull;
    @Override
    public void initialize(CGC constraintAnnotation) {
        canBeNull = constraintAnnotation.canBeNull();
    }
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return canBeNull || value != null;
    }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With