Repeating Annotations in Java 8 | @Repeatable | Onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Repeating Annotations in Java 8 are introduced for the support of having multiple same annotations to a declaration. Before Java 8 duplication annotations are not allowed.
Let’s take a use case of having a class Products which has variables with names of products and we want to attach annotations to define the names of countries where the product is manufactured. Prior to Java 8, since we don’t have support for multiple same annotations on the same declaration or type case, we create two different annotations and place on products variable as below.
Example:

Country1.java
Country1.java
public @interface Country1 {
    String name() default "";
}

Country2.java
Country2.java
public @interface Country2 {
    String name() default "";
}

Products.java
Products.java
public class Products {
    @Country1(name = "India")
    @Country2(name = "China")
    private String footBall;
}


Country1.java
Country1.java
public @interface Country1 {
    String name() default "";
}

public @interface Country1 {
    String name() default "";
}
Country2.java
Country2.java
public @interface Country2 {
    String name() default "";
}

public @interface Country2 {
    String name() default "";
}
Products.java
Products.java
public class Products {
    @Country1(name = "India")
    @Country2(name = "China")
    private String footBall;
}

public class Products {
    @Country1(name = "India")
    @Country2(name = "China")
    private String footBall;
}
Java 8 has introduced an annotation type called java.lang.annotation.Repeatable for annotating another annotation to inform the compiler that this annotation is Repeatable. This gives the developer flexibility to have multiple same annotations on a variable.
Usage:

Repeatable Annotation: The Repeating Annotation has to be annotated with @Repeatable to have the capability to repeat. We have to pass the class name as a parameter to the meta-annotation @Repeatable where the compiler can store all the multiple annotations and that acts as a container for values.

Example: Country.java
Country.java
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@Repeatable(value = Countries.class)
public @interface Country {
    String name();
}



Container Annotation: The container annotation can be declared as normal annotation and it has to have a value variable whose type is an array of above Repeatable annotation.

Example: Countries.java
Countries.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Countries {
    Country[] value() default {};
}



Implementation: Now the products class can define the same annotation multiple times on a single product.

Example: Products.
Products.java
public class Products {
    @Country(name = "India")
    @Country(name = "China")
    private String volleyBall;
}



Retrieving Annotations: We can retrieve annotation data by using Reflection API. getAnnotationsByType() is used to retrieve the annotation values. We can also use getAnnotation() method passing the Container Annotation class as input to it to retrieve the values.
RepeatingAnnotationsTest.java
import java.lang.reflect.Field;

public class RepeatingAnnotationsTest {

    public static void main(String[] args) throws NoSuchFieldException,
            SecurityException {
        Products products = new Products();
        Class<?> c = products.getClass();
        Field fd = c.getDeclaredField("volleyBall");
        Country[] countries = fd.getAnnotationsByType(Country.class);
        for (Country country : countries) {
            System.out.println(country.name());
        }
    }
}


Repeatable Annotation: The Repeating Annotation has to be annotated with @Repeatable to have the capability to repeat. We have to pass the class name as a parameter to the meta-annotation @Repeatable where the compiler can store all the multiple annotations and that acts as a container for values.

Example: Country.java
Country.java
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@Repeatable(value = Countries.class)
public @interface Country {
    String name();
}




Example: Country.java
Country.java
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@Repeatable(value = Countries.class)
public @interface Country {
    String name();
}


Example: Country.java
Country.java
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@Repeatable(value = Countries.class)
public @interface Country {
    String name();
}

import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@Repeatable(value = Countries.class)
public @interface Country {
    String name();
}
Container Annotation: The container annotation can be declared as normal annotation and it has to have a value variable whose type is an array of above Repeatable annotation.

Example: Countries.java
Countries.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Countries {
    Country[] value() default {};
}




Example: Countries.java
Countries.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Countries {
    Country[] value() default {};
}


Example: Countries.java
Countries.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Countries {
    Country[] value() default {};
}

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Countries {
    Country[] value() default {};
}
Implementation: Now the products class can define the same annotation multiple times on a single product.

Example: Products.
Products.java
public class Products {
    @Country(name = "India")
    @Country(name = "China")
    private String volleyBall;
}




Example: Products.
Products.java
public class Products {
    @Country(name = "India")
    @Country(name = "China")
    private String volleyBall;
}


Example: Products.
Products.java
public class Products {
    @Country(name = "India")
    @Country(name = "China")
    private String volleyBall;
}

public class Products {
    @Country(name = "India")
    @Country(name = "China")
    private String volleyBall;
}
Retrieving Annotations: We can retrieve annotation data by using Reflection API. getAnnotationsByType() is used to retrieve the annotation values. We can also use getAnnotation() method passing the Container Annotation class as input to it to retrieve the values.
RepeatingAnnotationsTest.java
import java.lang.reflect.Field;

public class RepeatingAnnotationsTest {

    public static void main(String[] args) throws NoSuchFieldException,
            SecurityException {
        Products products = new Products();
        Class<?> c = products.getClass();
        Field fd = c.getDeclaredField("volleyBall");
        Country[] countries = fd.getAnnotationsByType(Country.class);
        for (Country country : countries) {
            System.out.println(country.name());
        }
    }
}

import java.lang.reflect.Field;

public class RepeatingAnnotationsTest {

    public static void main(String[] args) throws NoSuchFieldException,
            SecurityException {
        Products products = new Products();
        Class<?> c = products.getClass();
        Field fd = c.getDeclaredField("volleyBall");
        Country[] countries = fd.getAnnotationsByType(Country.class);
        for (Country country : countries) {
            System.out.println(country.name());
        }
    }
}
Conclusion:
Though Repeating Annotations is a small addition to Java 8, it is a very useful change released in Annotation category, when all advanced frameworks configuration is moving towards annotation-based system from XML.
Happy Learning 🙂

Importance of using Java Annotations ?
Java 8 How to Convert List to String comma separated values
Default Static methods in Interface Java 8
Java Reflection Get Method Information
@Autowired,@Qualifier,@Value annotations in Spring
How HashMap Works In Java
Lambda Expressions in Java
Hibernate Table per Class strategy Annotations Example
Hibernate One To Many Using Annotations
Hibernate 4 Example with Annotations Mysql
What are Lambda Expressions in Java 8
User defined sorting with Java 8 Comparator
ArrayList in Java
How to Convert Java String to Int
Java 8 Stream API and Parallelism

Importance of using Java Annotations ?
Java 8 How to Convert List to String comma separated values
Default Static methods in Interface Java 8
Java Reflection Get Method Information
@Autowired,@Qualifier,@Value annotations in Spring
How HashMap Works In Java
Lambda Expressions in Java
Hibernate Table per Class strategy Annotations Example
Hibernate One To Many Using Annotations
Hibernate 4 Example with Annotations Mysql
What are Lambda Expressions in Java 8
User defined sorting with Java 8 Comparator
ArrayList in Java
How to Convert Java String to Int
Java 8 Stream API and Parallelism
 


Δ
 Install Java on Mac OS
 Install AWS CLI on Windows
 Install Minikube on Windows
 Install Docker Toolbox on Windows
 Install SOAPUI on Windows
 Install Gradle on Windows
 Install RabbitMQ on Windows
 Install PuTTY on windows
 Install Mysql on Windows
 Install Hibernate Tools in Eclipse
 Install Elasticsearch on Windows
 Install Maven on Windows
 Install Maven on Ubuntu
 Install Maven on Windows Command
 Add OJDBC jar to Maven Repository
 Install Ant on Windows
 Install RabbitMQ on Windows
 Install Apache Kafka on Ubuntu
 Install Apache Kafka on Windows
 Java8 – Install Windows
 Java8 – foreach
 Java8 – forEach with index
 Java8 – Stream Filter Objects
 Java8 – Comparator Userdefined
 Java8 – GroupingBy
 Java8 – SummingInt
 Java8 – walk ReadFiles
 Java8 – JAVA_HOME on Windows
 Howto – Install Java on Mac OS
 Howto – Convert Iterable to Stream
 Howto – Get common elements from two Lists
 Howto – Convert List to String
 Howto – Concatenate Arrays using Stream
 Howto – Remove duplicates from List
 Howto – Filter null values from Stream
 Howto – Convert List to Map
 Howto – Convert Stream to List
 Howto – Sort a Map
 Howto – Filter a Map
 Howto – Get Current UTC Time
 Howto – Verify an Array contains a specific value
 Howto – Convert ArrayList to Array
 Howto – Read File Line By Line
 Howto – Convert Date to LocalDate
 Howto – Merge Streams
 Howto – Resolve NullPointerException in toMap
 Howto -Get Stream count
 Howto – Get Min and Max values in a Stream
 Howto – Convert InputStream to String