简体   繁体   中英

Java - Custom/standard validation with Annotations

I'm using annotations in a project. The thing is i'm making custom validation that (partly) depends on annotations. I'm also making own annotations, but I want to use as much as I can from the JSR 303 standard.

to check if a field 'passes' the annotation constraints i've written some methods. Example:

static boolean isNotNullValid(Field f){
    boolean valid = true;
    if(f.isAnnotationPresent(NotNull.class)){
        Object o = ObjectGetter.getFieldValue(f);
        if(o==null){
            valid = false;
        }
    }
    return valid;
}

It's quite a lot of work to do this type of validation for all annotations. Is there some method i'm missing, like .isValid() ? I mean, of course, for the standard annotations.

Thanks in advance

You're not supposed to code that by yourself. You should instead rely on an implementation of the JSR, for example Hibernate Validator . The Validator it implements allows getting a set of constraint violations based on the annotations on the bean.

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