Java 当只有一个参数时无法识别可重复注释
Java Repeatable annotation not recognized when it's only one parameter
我想创建一个包含键值结构的选项 class。
这个Map在运行时填充了一个配置文件的内容。
为了验证我想要的配置,请为选项 class 的每个注释定义所需的键,例如:
// Map must contain a entry with key 'foo' and key 'bar'
@requiredKey("foo")
@requiredKey("bar")
class Options {
Map<String, String> optionsMap;
}
因此我创建了一个可重复的注解:
@Retention(RetentionPolicy.RUNTIME)
public @interface requiredKeys {
requireKey[] value();
}
@Repeatable(requiredKeys)
public @interface requredKey {
String value();
}
在运行时我调用 requiredKey[] anno = options.getAnnotationsByType(requiredKey.class))
如果指定的注解个数>1,这就可以正常工作。但是如果注解的个数恰好是一个,我就无法获取它(getAnnotationsByType
returns 一个空数组)
工作:
@requiredKey("foo")
@requiredKey("bar")
class Options {
Map<String, String> optionsMap;
}
// anno holds 'foo' and 'bar'
requiredKey[] anno = options.getAnnotationsByType(requiredKey.class))
不工作:
@requiredKey("foo")
class Options {
Map<String, String> optionsMap;
}
// anno is empty
requiredKey[] anno = options.getAnnotationsByType(requiredKey.class))
我不明白这种行为:(
所以我的问题是:
- 如何解释这种行为?
- 我怎样才能让它工作?
谢谢
您需要在 @requiredKey
中添加保留政策:
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(requiredKeys)
public @interface requredKey {
String value();
}
如果不这样做,那么当您创建带有一个注释的 class 时,Java 不会创建 requiredKeys
注释,因为您只有一个 Annotation
.因此,应用 @requiredKey
的保留策略。在你的例子中,你有 none,这意味着 JVM 将看不到你的注释。
其他评论:class/annotations.
请使用大写字母
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiredKeys {
requireKey[] value();
}
@Repeatable(RequiredKeys)
public @interface RequiredKey {
String value();
}
我想创建一个包含键值结构的选项 class。
这个Map在运行时填充了一个配置文件的内容。
为了验证我想要的配置,请为选项 class 的每个注释定义所需的键,例如:
// Map must contain a entry with key 'foo' and key 'bar'
@requiredKey("foo")
@requiredKey("bar")
class Options {
Map<String, String> optionsMap;
}
因此我创建了一个可重复的注解:
@Retention(RetentionPolicy.RUNTIME)
public @interface requiredKeys {
requireKey[] value();
}
@Repeatable(requiredKeys)
public @interface requredKey {
String value();
}
在运行时我调用 requiredKey[] anno = options.getAnnotationsByType(requiredKey.class))
如果指定的注解个数>1,这就可以正常工作。但是如果注解的个数恰好是一个,我就无法获取它(getAnnotationsByType
returns 一个空数组)
工作:
@requiredKey("foo")
@requiredKey("bar")
class Options {
Map<String, String> optionsMap;
}
// anno holds 'foo' and 'bar'
requiredKey[] anno = options.getAnnotationsByType(requiredKey.class))
不工作:
@requiredKey("foo")
class Options {
Map<String, String> optionsMap;
}
// anno is empty
requiredKey[] anno = options.getAnnotationsByType(requiredKey.class))
我不明白这种行为:(
所以我的问题是:
- 如何解释这种行为?
- 我怎样才能让它工作?
谢谢
您需要在 @requiredKey
中添加保留政策:
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(requiredKeys)
public @interface requredKey {
String value();
}
如果不这样做,那么当您创建带有一个注释的 class 时,Java 不会创建 requiredKeys
注释,因为您只有一个 Annotation
.因此,应用 @requiredKey
的保留策略。在你的例子中,你有 none,这意味着 JVM 将看不到你的注释。
其他评论:class/annotations.
请使用大写字母@Retention(RetentionPolicy.RUNTIME)
public @interface RequiredKeys {
requireKey[] value();
}
@Repeatable(RequiredKeys)
public @interface RequiredKey {
String value();
}