简体   繁体   English

Java-带注释的自定义/标准验证

[英]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. 我也在制作自己的注释,但是我想尽可能多地使用JSR 303标准。

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() ? 我缺少一些方法,例如.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 . 相反,您应该依赖JSR的实现,例如Hibernate Validator The Validator it implements allows getting a set of constraint violations based on the annotations on the bean. 它实现的Validator允许根据Bean上的注释获得一组约束违规。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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