JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

@Repeatable Annotation in Java 8

December 16, 2013 by Krishna Srinivasan Leave a Comment

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.

[code lang=”java”]
@interface Anna { int value(); }

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

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

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

@Annas({@Anna(1), @Anna(2)})
class JavaBeat{}
[/code]

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,

[code lang=”java”]

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

[/code]

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.

Filed Under: Java Tagged With: Java 8

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.

Leave a Reply Cancel reply

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.

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved