✅ What Is a Repeatable Annotation?
It means you can write something like this:
@Hint("first hint")
@Hint("second hint")
public class MyClass { }
To make this possible, you need to define:
- The repeatable annotation
- A container annotation that holds multiple instances
✅ Step-by-Step: Define a Repeatable Annotation
🔹 1. Define the Repeatable Annotation
import java.lang.annotation.*;
@Repeatable(Hints.class) // points to the container
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) // can apply to class, adjust as needed
public @interface Hint {
String value();
}
🔹 2. Define the Container Annotation
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Hints {
Hint[] value();
}
🔹 3. Use It
@Hint("first")
@Hint("second")
public class MyClass { }
🔍 Retrieve Annotations via Reflection:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Hint[] hints = MyClass.class.getAnnotationsByType(Hint.class);
Arrays.stream(hints).forEach(h -> System.out.println(h.value()));
}
}
🧠 Summary
Component | Purpose |
---|---|
@Repeatable(...) | Declares the annotation as repeatable |
Container annotation (Hints ) | Stores multiple @Hint annotations |
Reflection | Use getAnnotationsByType() to retrieve them |