@Repeatable Annotation in Java 8

There are many features in the Java 8 release. Only few of them are discussed in the blogs and few are not noticed by many developers are not advertised as it is not popularly used by the common developers. One of such feature is the introduction of @Repeatable annotation which tells the compiler that that annotation can be used multiple times. Prior to Java 8, duplicate annotations are not allowed in a class. The following annotation is not valid.

@interface Anna { int value(); }

@Anna(1) @Anna(2) // error: Duplicate annotation
class JavaBeat{}

To overcome the above drawback, you have to define another annotation as below.

<pre>@interface Anna { int value(); }
@interface Annas {
   Anna[] value();
}

@Annas({@Anna(1), @Anna(2)})
class JavaBeat{}

With @Repeatable annotation in Java 8, we are no longer worried about using the same annotation multiple times in a class. In normal scenario, these annotation will be used by those who are writing the custom annotations, it means the creator of annotation. When you write the same above annotation, the definition would look like this,


@Repeatable(Annas.class)
public @interface Anna { ... }

When you use the above annotation in the code, just use it multiple times, when code compiles the compiler internally does the same way how we have wrapped the list of annotations in the array. The only advantage is that programmer need not worry about the extra syntax. Compiler takes care of combining all the similar annotations.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better