data-driven-docs

Selft training repo


Project maintained by ggranados Hosted on GitHub Pages — Theme by mattgraham

Repeating Annotations



Overview

Allow multiple annotations of the same type to be declared on a single program element.

To enable repeating annotations, the @Repeatable meta-annotation is used on the annotation type. This meta-annotation specifies a container annotation that holds multiple instances of the target annotation.

The container annotation is automatically generated by the Java compiler

   import java.lang.annotation.*;

   @Repeatable(Fruits.class)
   public @interface Fruit {
   String value();
   }
   
   @Retention(RetentionPolicy.RUNTIME)
   public @interface Fruits {
   Fruit[] value();
   }
   
   @Fruit("Apple")
   @Fruit("Orange")
   public class FruitBasket {
   // ...
   }

Examples

Here’s a real-world example of how repeating annotations can be used:

Consider a scenario where you want to annotate a class with multiple roles for access control purposes. Each role can be represented by an annotation. With repeating annotations, you can easily assign multiple roles to a class.

First, let’s define the annotation types:

import java.lang.annotation.*;

@Repeatable(Roles.class)
public @interface Role {
    String value();
}

@Retention(RetentionPolicy.RUNTIME)
public @interface Roles {
    Role[] value();
}

Next, let’s annotate a class with multiple roles:

@Role("admin")
@Role("user")
public class MyClass {
    // Class implementation
}

In this example, the MyClass is annotated with two roles: admin and user. The @Role annotation is marked as @Repeatable with the container annotation @Roles.

Now, let’s see how we can retrieve the repeated annotations at runtime:

import java.lang.annotation.Annotation;

public class Main {
    public static void main(String[] args) {
        Class<MyClass> clazz = MyClass.class;
        Roles rolesAnnotation = clazz.getAnnotation(Roles.class);
        if (rolesAnnotation != null) {
            Role[] roles = rolesAnnotation.value();
            for (Role role : roles) {
                System.out.println("Role: " + role.value());
            }
        }
    }
}

In this example, we use reflection to obtain the Roles annotation from the MyClass class. We then retrieve the array of Role annotations and iterate over them to print out each role value.


Ref.

Starting from Spring Framework 4.0, Spring introduced support for repeating annotations.It leverages Java’s @Repeatable meta-annotation and provides utility methods to work with repeating annotations.1


Get Started | Languages | Java Development | Java 8


  1. https://www.baeldung.com/spring-core-annotations