Java.Java8.How to define repeatable annotation?

✅ 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:

  1. The repeatable annotation
  2. 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

ComponentPurpose
@Repeatable(...)Declares the annotation as repeatable
Container annotation (Hints)Stores multiple @Hint annotations
ReflectionUse getAnnotationsByType() to retrieve them
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.