Java 以前版本的 8 个可重复注释模拟

Java 8 repeatable annotations analog for prior versions

如果你想重复注释java 8 允许。

示例:

@Retention(RetentionPolicy.RUNTIME)
@Repeatable(MyAnnotationContainer.class)
@interface MyAnnotation {

    String value();

}

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotationContainer {

    MyAnnotation[] value();
}

@MyAnnotation( "a")
@MyAnnotation( "b")
class MyClass {
}

在描述中我读到它只是提示 java 编译器生成代码。

请说明此代码在 java 5-7 中的外观如何?

在 Java 8 之前,需要像这个例子一样显式包装注释:

@MyAnnotationContainer({
  @MyAnnotation("a"),
  @MyAnnotation("b")
})
class MyClass {
}

这也是在运行时通过反射公开注释的方式 API。 Java 8 只为这个显式包装添加了一些 syntactic suggar,因为这是一个常见的用例。