java - 在省略号前输入注解

标签 java annotations type-annotation

我在 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) {}

关于java - 在省略号前输入注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31944980/

相关文章:

java - 使用 Java 6/7 编译的注释可以用于 Java 8 中的类型参数吗?

java-8 可选双重检查

java - 显示同一类方法的弃用警告

c# - 使用 iTextSharp 读取 PDF 文件附件注释

java - Eclipse 不喜欢 @Override 注释

scala - 如何修复 Scala 的 WartRemover 工具中的产品类型推断错误

java - 是否可以在运行时访问 Java 8 类型信息?

java - 静态方法 - 何时将数组参数返回为 void 并返回为数组?

java - log4j2 定期清理日志文件

java - 在单独的线程中出现 NetworkOnMainThreadException