Java可重复注释在';只有一个参数

Java可重复注释在';只有一个参数,java,annotations,Java,Annotations,我想创建一个包含键值结构的选项类 此映射在运行时填充配置文件的内容 要验证该配置,我需要为Option类的每个注释定义所需的键,如: // Map must contain a entry with key 'foo' and key 'bar' @requiredKey("foo") @requiredKey("bar") class Options { Map<String, String> optionsMap; } 在运行时,我调用requiredKey[]anno=

我想创建一个包含键值结构的选项类

此映射在运行时填充配置文件的内容

要验证该配置,我需要为Option类的每个注释定义所需的键,如:

// Map must contain a entry with key 'foo' and key 'bar'
@requiredKey("foo")
@requiredKey("bar")
class Options {
   Map<String, String> optionsMap;
}
在运行时,我调用
requiredKey[]anno=options.getAnnotationsByType(requiredKey.class))

如果指定注释的数量大于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”)
@所需密钥(“bar”)
类选项{
地图选项地图;
}
//安诺持有“foo”和“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(“foo”)
类选项{
地图选项地图;
}
//阿诺是空的
requiredKey[]anno=options.getAnnotationsByType(requiredKey.class))
我不明白这种行为:(

因此,我的问题是:

  • 对这种行为有什么解释
  • 我怎样才能让它工作

谢谢

您需要在
@requiredKey
中添加保留策略:

@Retention(RetentionPolicy.RUNTIME)
@Repeatable(requiredKeys)
public @interface requredKey {
    String value();
}
如果没有,那么当您使用一个注释创建一个类时,Java不会创建
requiredKeys
注释,因为您只有一个
注释
。因此,将应用
@requiredKey
的保留策略。在您的情况下,您没有注释,这意味着您的注释不会被JVM看到

其他注释:请使用大写字母作为课堂/注释

@Retention(RetentionPolicy.RUNTIME)
public @interface RequiredKeys {
    requireKey[] value();
}

@Repeatable(RequiredKeys)
public @interface RequiredKey {
    String value();
}
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiredKeys {
    requireKey[] value();
}

@Repeatable(RequiredKeys)
public @interface RequiredKey {
    String value();
}