What does the default ""
part mean in the following code?
public @interface MyAnnotation {
String[] names() default "";
}
Is it equal to
String[] names() default new String[0];
?
What does the default ""
part mean in the following code?
public @interface MyAnnotation {
String[] names() default "";
}
Is it equal to
String[] names() default new String[0];
?
public @interface MyAnnotation {
String[] names() default "";
}
means that by default names
will be an array of one empty String
(""
).
This is the same as if you've used the array-initializer:
public @interface MyAnnotation {
String[] names() default { "" };
}
Additionally, String[] names() default new String[0];
doesn't compile, because the (default) value of an annotation property must be a constant expression.
As a homework, you can annotate something with MyAnnotation
and explore its properties with Reflection.
It is equivalent to an array with a single element consisting of the empty string. From the Java Language Specification section 9.7.1 on annotations:
If the element type is an array type, then it is not required to use curly braces to specify the element value of the element-value pair. If the element value is not an ElementValueArrayInitializer, then an array value whose sole element is the element value is associated with the element. If the element value is an ElementValueArrayInitializer, then the array value represented by the ElementValueArrayInitializer is associated with the element.