类中的变量注释

时间:2018-03-04 17:08:03

标签: java validation annotations

最近,我看到了一个使用注释验证字段的示例:

Class Foo{
    @Min(2)
    int x;
}

我知道我可以访问注释接口中声明的函数,如:

//UPDATE: missing code
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Min {
    int x() default 0;
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Afoo {
    String msg() default "Oy!";
}

@Afoo(msg = "Hi!")
class Foo{
//    @Min(3)
    public int x;
}

public class Test{
    public static void main(String[] args) {
        Class c = Foo.class;
        Annotation an = c.getAnnotation(Afoo.class);
        Afoo a = (Afoo)an;

        System.out.println(a.msg());
    }

}

但是,当我取消注释行

//    @Min(3)

并创建一个名为Min的新注释界面,我有一个错误说:

  

注释类型不适用于此类声明。

所以,即使我可以访问此功能,我怎么知道它与x有关?

1 个答案:

答案 0 :(得分:3)

假设您自己的Min注释版本的声明本身已使用@Target(ElementType.TYPE)进行注释,则@Target是错误的。 ElementType.TYPEfor classes, interfaces and enum declarations。您不想注释类型,您想要注释字段x。使用

@Target(ElementType.FIELD)

代替。