1

Read about How to set String Array in Java Annotation

I have a query, for below code:

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

Expecting a syntax String[] owners() default {}. How Java compiler allow string literal syntax("") for String[] type parameter(owners)?

Naman
  • 27,789
  • 26
  • 218
  • 353
overexchange
  • 15,768
  • 30
  • 152
  • 347
  • 1
    Both versions are acceptable. `default ""` is like `default {""}` so default value is array with *one* element: empty string. If you set `default {}` then default value is *empty* array. – Pshemo Sep 17 '17 at 10:29
  • The array with an empty string. You can also put a single string "default" in there as well or `{}` simply for an empty array. – Naman Sep 17 '17 at 10:30

1 Answers1

1

As marked in the comments as well, the default value "" for the annotation key owners creates an array with an element that's an empty string. You can also put a single string "default" in there as well which would lead to creating an array with only value "default"

OR

{} simply for an empty array if the need be.


To test this you can mark the annotation with Runtime retention policy as :

@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;
}

Annotate a class with this

@Unfinished(value = "")
public class AnnotatedClass {

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

and then use Reflection to get the values of the keys of Unfinished as :

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()));
    }
}
Naman
  • 27,789
  • 26
  • 218
  • 353