4

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;
    }
    ...

1 Answer 1

12

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.