Over a million developers have joined DZone.

Repeatable Annotations in Java 8

DZone's Guide to

Repeatable Annotations in Java 8

Do you use repeating annotations in your code? Here's an alternative approach that could make your annotations more compact and readable.

· Java Zone ·
Free Resource

Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now.

With Java 8, you are able to repeat the same annotation to a declaration or type. For example, to register that one class should only be accessible at runtime by specific roles, you could write something like:

public class AccountResource {

Notice that @Role is stated twice. For compatibility reasons, repeating annotations are stored in a container annotation, so instead of writing just one annotation, you need to write two, so in the previous case, you need to create @Role and @Roles annotations.

Notice that you need to create two annotations, one of which is the "plural" part of the annotation where you set the return type of the value method to be an array of the annotation that can be used multiple times. The other annotation can be used multiple times in the scope where it is defined and must be annotated with the @Repeatable annotation.

This is how I did it all the time, since Java 8 allows you to do it. But during a code review last week, my mate George Gastaldi pointed out how they are implementing these repeatable annotations in javax.validation spec. Of course, it is not completely different, but I think that looks pretty clear from the implementation point of view, since everything is implemented within the same archive and also, in my opinion, the name looks much more natural.

public @interface Role {

    String value();

    @interface List {
        Role[] value();

Notice that everything is placed in the same archive. Since, usually, you only need to refer to the @Role class and not the @Roles (now @Role.List) annotation. You can hide this annotation as an inner annotation. Also, in the case of defining several annotations, this approach makes everything look more compact. Instead of populating the hierarchy with "duplicated" classes serving the same purpose, you only create one.

Of course, I am not saying that the approach of having two classes is wrong. At the end of the day, it is about preferences, since both are really similar. But after implementing repeatable annotations in this way, I think that it is cleaner and more compact solution, having everything defined in one class.

Connect any Java based application to your SaaS data.  Over 100+ Java-based data source connectors.

java ,repeatable annotations ,java 8 ,code readability ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}