Repeatable Annotation using Java 8

1. Overview

Prior to Java 8, it was forbidden to declare more than one annotation of the same type to the same part of the code (e.g. a class or a method). Java 8 brought a small yet very useful improvement called repeating annotations which allows us to use the same annotations can be repeated as much as you want at same locations.

2. Repeatable Annotation Usage

Until Java 7, to have a repeated annotation, developers have to group them together in a container annotation like below:

With Java 8 repeated annotation, we have flexibility to write the same thing without any container annotation like below:

For compatibility reasons, since this feature was introduced in Java 8, repeating annotations are stored in a container annotation that is automatically generated by the Java compiler.

3. How to Declare?

3.1 Declare a Repeatable Annotation Type

The annotation type must be marked with the @Repeatable meta-annotation. The following example defines a custom @Author repeatable annotation type:

3.2 Declare the Containing Annotation Type

Define the containing annotation with a mandatory value element, and whose type must be an array of the repeatable annotation type:

Now, we can use @Author multiple times:

4. Benefits

Sometimes, you want to apply the same annotation multiple times. Before Java 8, the only way to do that was to use an additional annotation and provide an array of the annotations you want to apply as a value. The most common annotations with JPA and Hibernate are the @NamedQuery, @AttributeOverride and @NamedQueries, @AttributeOverrides etc.

5. Conclusion

Repeating annotations is a syntactic sugar to Java which simplifies usage of some annotations in various frameworks (especially in Hibernate and JPA).

Thank you.

 

harinathk
 

Click Here to Leave a Comment Below 0 comments