Java 8 Duplicate Annotations for Previous Versions

If you want to repeat java 8 annotation, enable this.

Example:

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

    String value();

}

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotationContainer {

    MyAnnotation[] value();
}

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

In the description, I read that this is just a hint at the java compiler to generate the code.

Clarify what this code looks like in java 5-7?

+4
source share
1 answer

Before Java 8, annotations will need to be explicitly wrapped, as in this example:

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

It is also the way that annotations are displayed at run time through the reflection API. Java 8 only added some syntactic advar for this explicit packaging, as this is a common use case.

+6
source

Source: https://habr.com/ru/post/1608771/


All Articles