Java Annotation @Repeatable
In Java, the @Repeatable
annotation is used to specify that an annotation can be used more than once on the same element. Prior to Java 8, it was not possible to use an annotation more than once on the same element, but with the introduction of the @Repeatable
annotation, it is now possible.
To use the @Repeatable
annotation, you need to define the annotation that can be repeated as a container annotation, which will hold one or more instances of the annotation being repeated. The container annotation must have a value attribute that returns an array of the repeated annotations.
Here is an example of an annotation with the @Repeatable
annotation applied to it:
import java.lang.annotation.Repeatable; @Repeatable(Fruits.class) public @interface Fruit { String name() default ""; String color() default ""; }
In the example above, the @Repeatable
annotation is applied to the Fruit
annotation. This means that the Fruit
annotation can be repeated on the same element, such as a method or class.
To repeat the Fruit
annotation, you need to define a container annotation, as follows:
public @interface Fruits { Fruit[] value(); }
The Fruits
annotation is a container annotation that holds an array of Fruit
annotations. This allows the Fruit
annotation to be used more than once on the same element, as in the following example:
@Fruit(name = "Apple", color = "Red") @Fruit(name = "Banana", color = "Yellow") public class MyClass { // ... }
In this example, the Fruit
annotation is repeated twice on the MyClass
class using the @Fruit
container annotation.