【发布时间】: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