javaannotationstype-annotation

Type annotations before ellipsis


I've seen in the JLS section 8.4 that there can be annotations before an ellipsis:

class X {
    void method(String @Annotation ... x) {}
}

My question is then rather simply: what does it mean?

In particular, what is the difference with:

class X {
    void method(@Annotation String ... x) {}
}

Solution

  • When you write a varargs formal parameter such as

    void method(String... x) {}
    

    then the Java compiler generates a method that takes an array of strings; whenever your source code calls the method with multiple arguments, the Java compiler packages them up into an array before calling the method. So, it is helpful to think of a declaration like String... as being akin to String[]. Furthermore, the annotations are interpreted the same.

    Either of these annotations

    void method(String @NonEmpty ... x) {}
    void method(String @NonEmpty [] x) {}
    

    applies to the array: the type means a non-empty array of strings. The annotation documents that the array or vararg list should not be empty. You could use an annotation processor to enforce this at compile time or run time.

    Either of these annotations

    void method(@English String ... x) {}
    void method(@English String [] x) {}
    

    applies to the element type. The annotation documents that the method takes an array of English strings.