在省略号前输入注解

Type annotations before ellipsis

我在 JLS section 8.4 中看到省略号前可以有注释:

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

我的问题很简单:这是什么意思?

具体来说,与以下有什么区别:

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

From the JLS on Where Annotations May Appear

It is possible for an annotation to appear at a syntactic location in a program where it could plausibly apply to a declaration, or a type, or both.

Whether an annotation applies to a declaration or to the type of the declared entity - and thus, whether the annotation is a declaration annotation or a type annotation - depends on the applicability of the annotation's type: [...]

因此,

中的注释
void method(String @Annotation ... x) {}

是一个 TYPE_USE 注释。

以及

中的注解
void method(@Annotation String ... x) {}

既是 TYPE_USE 又是 PARAMETER 注释。


你可以验证一下。

@Target(value = ElementType.TYPE_USE)
@interface Annot {}
public static void method(String @Annot... arg) {}
public static void method2(@Annot String... arg) {}

@Target(value = ElementType.PARAMETER)
@interface Annot {}
public static void method(String @Annot... arg) {} // DOES NOT COMPILE
public static void method2(@Annot String... arg) {}

当你写一个 varargs 形参如

void method(String... x) {}

然后 Java 编译器生成一个接受字符串数组的方法;每当您的源代码使用多个参数调用该方法时,Java 编译器会在调用该方法之前将它们打包到一个数组中。因此,将 String... 之类的声明视为类似于 String[] 是有帮助的。此外,注释的解释相同。

这些注释中的任何一个

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

适用于数组:该类型表示非空字符串数组。数组或可变参数列表不应为空的注释文档。您可以使用注释处理器在编译时或 运行 时强制执行此操作。

这些注释中的任何一个

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

适用于元素类型。注释记录该方法采用英文字符串数组。