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.
Join the DZone community and get the full member experience.
Join For FreeWith 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:
@Role("admin")
@Role("manager")
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.
@Repeatable(Role.List.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Role {
String value();
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@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.
Published at DZone with permission of Alex Soto, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments