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];
?
Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.
Annotation types are a form of interface, which will be covered in a later lesson. For the moment, you do not need to understand interfaces. The body of the previous annotation definition contains annotation type element declarations, which look a lot like methods. Note that they can define optional default values.
Java Custom Annotations The @interface element is used to declare an annotation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With