Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array elements in annotations used as single values

What happens when we declare an array in an Annotation and use it like this:

@interface MyAnno {
    String[] names();
}

@MyAnno(names="some value")
class { ... }

Although the element names is declared as an Array of String, we can use it as a String, providing a single value without curly braces. I guess that's a good thing and that's how SuppressWarnings work, I just want to know what happens internally when we do that? How the compiler handles this? Does it replace names with a String named names, or applies {} where the annotation is used? Something else?


1 Answers

From the Java Language specification:

Identifier = ElementValue

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.

It's syntactic sugar - you get an array with a single element.

like image 76
laune Avatar answered Sep 07 '25 23:09

laune