Repeating Annotations

by | Apr 16, 2021 | Java

Home » Java » Repeating Annotations

Repeating Annotations

With the induction of Java 8 into the platform, you can now use two new annotations, namely, type annotations and repeating annotations. As the name suggests, repeating annotations provide you with an opportunity to reuse a particular annotation within the same class. The syntax of a repeating annotation is not very different to how you declare normal annotations. You can replace annotations with repeating annotations anywhere in your code.

Container annotation stores repeating annotations. This process is automatically executed by the compiler to ease the compatibility of the program. In such cases, the compiler requires the following two declarations in your code:

  1. Declaring a repeating annotation type
  2. Declaring the containing annotation type

Declaring a Repeatable Annotation Type

When you are declaring a repeatable annotation type, it must be marked with @Repeatable meta-annotation. The following example defines a custom @Game repeatable annotation type.

@Repeatable (Games.class)
@interfaceGame {
String name ();
String delay ();
}

 

Declaring the containing annotation type

This containing type annotation must have a value element and an array type. The data type of the array must be of the repeating annotation type component.

@interfaceGames
{
Game [] value ();
}

 

Sample Program

This program shows an example of repeating annotations

import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Repeatable (Games.class)
@interfaceGame
{
String name();
String day ();
}
@Retention (RetentionPolicy.RUNTIME)
@nterfaceGames {
Game [] value ();
}
@Game (name = “Cricket”, day = “Sunday”)
@Game (name = “Hockey”, day = “Friday”)
@Game (name = “Football”, day = “Saturday”)
public class RepeatingAnnotationsExample
{
public static void main (String args [])
{
Game [] game = RepeatingAnnotationsExample.class.getAnnotationsByType(Game.class);
for (Gamegame2 : game)
{
System.out.println (game2.name() + “on” + game2.day());
}
}
}

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author