注释参数 - String []类型参数设置为字符串文字

时间:2017-09-17 10:16:27

标签: java annotations variadic-functions

了解How to set String Array in Java Annotation

我有一个查询,代码如下:

@Unfinished("Just articleware")
public @interface Unfinished {
    public enum Priority {LOW, MEDIUM, HIGH}
    String value();
    String[] owners() default "";
    Priority priority() default Priority.MEDIUM;
}

期望语法String[] owners() default {}。 Java编译器如何为""类型参数(String[])提供字符串文字语法(owners)?

1 个答案:

答案 0 :(得分:1)

如注释中所标记的,注释键""的默认值owners创建一个元素为空字符串的数组。你也可以在其中放置一个字符串"default",这将导致创建一个只有值“default”的数组

OR

{}如果需要,只需要一个空数组。

要对此进行测试,您可以使用运行时保留策略将注释标记为:

@Unfinished("Just articleware")
@Retention(RetentionPolicy.RUNTIME) // mark with Runtime retention policy
public @interface Unfinished {
    enum Priority {LOW, MEDIUM, HIGH}

    String value();

    String[] owners() default "";

    Priority priority() default Priority.MEDIUM;
}

使用此

注释一个类
@Unfinished(value = "")
public class AnnotatedClass {

    public static void main(String[] args) {
        System.out.println("");
    }
}

然后使用Reflection将Unfinished的键值设为:

public static void main(String[] args) throws Exception {
    System.out.println("Testing...");
    Class<AnnotatedClass> obj = AnnotatedClass.class;
    if (obj.isAnnotationPresent(Unfinished.class)) {
        Annotation annotation = obj.getAnnotation(Unfinished.class);
        Unfinished unfinished = (Unfinished) annotation;
        System.out.println(Arrays.toString(unfinished.owners()));
    }
}