【问题标题】:Annotations on a variable, inside a class [closed]类内变量的注释[关闭]
【发布时间】:2018-03-04 17:08:02
【问题描述】:

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

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有关?

【问题讨论】:

  • "所以即使我可以访问这个函数,我怎么知道它与 x 有关?" - 我不明白这个问题。
  • 最小定义在哪里/如何定义?
  • 这里的代码甚至不是有效的Java。请提供Minimal, Complete, and Verifiable example 您正在尝试做的事情。

标签: java validation annotations


【解决方案1】:

假设你自己版本的Min注解的声明本身是用@Target(ElementType.TYPE)注解的,那么@Target是错误的。 ElementType.TYPEfor classes, interfaces and enum declarations。你不想注释类型,你想注释一个字段x。使用

@Target(ElementType.FIELD)

改为。

【讨论】:

    猜你喜欢
    • 2018-03-18
    • 2017-04-25
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 2020-02-24
    • 2020-12-05
    • 2018-03-13
    • 1970-01-01
    相关资源
    最近更新 更多