简体   繁体   中英

How to use an annotation element inside a custom constraint validator

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM