Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Repeatable Annotations: Syntax and Usage

How to declare and read repeatable annotations in Java, including container annotation requirements and reflection usage.

~6 min readJava
#Java#Annotations#Reflection#Java 8
A diagram showing multiple annotation tags being grouped into a single container annotation in Java.

In Java, an annotation type is normally limited to one occurrence per declaration. The repeatable annotation feature, introduced in Java 8, allows the same annotation to appear multiple times on a single element. This is useful when a single element needs multiple values for the same annotation type, such as multiple test tags or multiple validation rules. Without repeatable annotations, developers had to resort to arrays of annotations or nested containers, which made the code verbose and harder to read.

Declaring a Repeatable Annotation

To make an annotation repeatable, define the annotation itself and a container annotation that holds an array of the repeatable annotation. Annotate the repeatable annotation with @Repeatable, and give the container a value() method that returns an array of the repeatable annotation type.

Here is a minimal example:

java
import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @Repeatable(Tags.class) public @interface Tag { String value(); } @Retention(RetentionPolicy.RUNTIME) public @interface Tags { Tag[] value(); }

In this example, @Tag is the repeatable annotation, and @Tags is the container. The @Repeatable annotation takes the container class as its argument. The container must be declared with a value() method that returns an array of the repeatable annotation type. The container and the repeatable annotation must have the same @Target and @Retention, or the compiler will reject the declaration. The @Retention(RetentionPolicy.RUNTIME) declarations in the example make both annotations visible to the reflection calls later in this article.

Once declared, you can apply @Tag multiple times to the same element:

java
@Tag("api") @Tag("performance") public class Service { // ... }

Without the container, the compiler would complain about a duplicate annotation. With the container, the compiler automatically wraps the repeated annotations in an instance of @Tags.

Reading Repeatable Annotations via Reflection

When you access annotations at runtime, reflection gives you several methods. getAnnotations() returns all annotations present, including the generated container. getAnnotationsByType() is the more targeted option for repeatable annotations: it looks through the container and returns the individual repeatable annotations.

Consider the following code:

java
public class AnnotationReader { public static void main(String[] args) throws Exception { Tag[] tags = Service.class.getAnnotationsByType(Tag.class); for (Tag tag : tags) { System.out.println(tag.value()); } } }

getAnnotationsByType() is the preferred method for reading repeatable annotations because it hides the container implementation. It works for repeatable annotations and for non-repeatable annotations; for a non-repeatable annotation it returns a one-element array when the annotation is present, and an empty array otherwise. This method is available since Java 8 and is the standard way to retrieve repeated annotations.

If you use getAnnotation(Tag.class) directly on an element that has repeated @Tag annotations, it will return null because the actual stored annotation is the container @Tags, not @Tag. To access the individual values, you must call getAnnotation(Tags.class) and then iterate over the array:

java
Tags container = Service.class.getAnnotation(Tags.class); if (container != null) { for (Tag tag : container.value()) { System.out.println(tag.value()); } }

This approach is more verbose and exposes the container type, which is an implementation detail. In most cases, getAnnotationsByType() is the better choice.

Common Mistakes with Container Annotations

Several pitfalls can cause compilation errors or unexpected runtime behavior when working with repeatable annotations.

One common mistake is forgetting to declare the container with the same retention and target as the repeatable annotation. For example, if @Tag has @Retention(RetentionPolicy.RUNTIME) but @Tags has @Retention(RetentionPolicy.CLASS), the compiler will produce an error. Both must match exactly.

Another mistake is declaring the container's value() method with a return type that is not an array of the repeatable annotation. The method must be named value and return an array of the exact repeatable type. Any other signature will cause a compilation error.

A related issue is using the container annotation manually. The container is intended to be generated by the compiler when it sees repeated @Tag annotations. Manual use is possible because the container annotation is a normal annotation, but it is usually unnecessary; mixing a manual @Tags with repeated @Tag annotations can produce confusing reflection results. Prefer repeated @Tag annotations so the compiler manages the container.

Finally, remember that the repeatable annotation and its container must be declared in the same compilation unit. If they are in different files, the compiler will not recognize the relationship, and you will get an error.

Runtime Behavior and Reflection Overhead

At runtime, repeated annotations are stored as a single container annotation. This means that when you call getAnnotations(), you will see the container, not the individual annotations. The getAnnotationsByType() method performs the flattening internally, but it still has to read the container and then expand its array.

This indirection has a small performance cost. For most applications, the overhead is negligible because reflection is rarely a hot path. However, if you are scanning a large number of classes or methods, the repeated array allocation and iteration can add up. If performance is critical, consider caching the results of getAnnotationsByType() or using compile-time annotation processing instead of runtime reflection.

Another runtime consideration is that the order of repeated annotations is preserved. The compiler stores them in the order they appear in the source code, and getAnnotationsByType() returns them in that same order. This is useful when the order carries meaning, such as a sequence of validation steps.

Compatibility and Maintainability Considerations

Repeatable annotations were introduced in Java 8. If your codebase must run on older Java versions, you cannot use this feature directly. You would need to fall back to a single annotation with an array of values, or use a container annotation manually. When upgrading, be aware that libraries that consume annotations may not be updated to handle repeatable annotations, so you should test compatibility.

From a maintainability perspective, repeatable annotations make the source code cleaner when multiple instances of the same annotation are needed. For example, instead of writing:

java
@Tags({@Tag("api"), @Tag("performance")})

you can write:

java
@Tag("api") @Tag("performance")

The latter is more readable and easier to edit. However, if you need to handle a variable number of values that are only known at runtime, annotations are not the right tool; consider configuration or a separate data structure instead.

When to Use Repeatable Annotations

Repeatable annotations are ideal when the number of instances is fixed at compile time and each instance carries a distinct value. Common use cases include:

  • Multiple test tags or categories on a test method.
  • Multiple validation rules on a field.
  • Multiple security roles for an endpoint.
  • Multiple configuration flags for a component.

They are less suitable when the values are dynamic or when you need to pass them through a configuration file. In those cases, annotations generally are not the right mechanism; use a separate data structure or configuration model instead.

Another consideration is tooling support. Some annotation processors and frameworks may not handle repeatable annotations correctly, especially if they were written before Java 8. Before adopting repeatable annotations, verify that your build tools and libraries can process them.

When you do use them, always prefer getAnnotationsByType() over manual container handling. This keeps your code independent of the container implementation and makes it easier to change the annotation design later. If you later change the annotation's shape, reflection code that uses getAnnotationsByType() is less coupled to the container, but callers may still need source changes if the annotation's API changes.

Repeatable annotations are a language feature that simplifies metadata declaration. They are not a performance optimization, nor do they change the semantics of annotations. They are purely a syntactic convenience that reduces boilerplate and improves readability. By following the container requirements and using the right reflection methods, you can integrate them cleanly into your codebase.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.