我想创建一个包含键值结构的选项类。
此映射在运行时填充有配置文件的内容。
为了验证配置,我想要为 Option 类的每个注释定义所需的键,例如:
// 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,则效果很好。但是,如果注释的数量恰好是 1,我无法获取它(getAnnotationsByType
返回一个空数组)
工作:
@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();
}
如果不这样做,那么当您使用一个注释创建类时,Java 不会创建 requiredKeys
注释,因为您只有一个 Annotation
。因此,应用 @requiredKey
的保留策略。在您的例子中,您没有任何注释,这意味着 JVM 将看不到您的注释。
其他评论:请在您的类/注释中使用大写字母。
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiredKeys {
requireKey[] value();
}
@Repeatable(RequiredKeys)
public @interface RequiredKey {
String value();
}
关于Java可重复注释只有一个参数时无法识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59739618/