Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is default "" for String[] in annotation declaration?

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];

?

like image 577
Jin Kwon Avatar asked Dec 18 '15 16:12

Jin Kwon


People also ask

What is @interface annotation in Java?

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.

What is an annotation type?

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.

Which annotation is used to declare the custom annotation?

Java Custom Annotations The @interface element is used to declare an annotation.


2 Answers

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.

like image 92
Konstantin Yovkov Avatar answered Sep 21 '22 05:09

Konstantin Yovkov


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.

like image 27
M A Avatar answered Sep 23 '22 05:09

M A