[JSR308] Strawman proposal for repeated annotations

Joseph D. Darcy Joe.Darcy at Sun.COM
Fri Nov 16 14:28:40 EST 2007


One of the design choices of annotations as introduced in JSR 175 is 
that repeated annotations are not allowed; that is, there can be at most 
one application of a particular annotation to a given element.

Various Java EE users of annotations wanted the ability of have multiple 
annotations; the workaround using JSR 175 is to have a second container 
annotation with an array-valued member, something like

@interface MyAnnotation {
    int value();

@interface MyRepeatedAnnotationContainer {
    MyAnnotation [] value();

Addressing this limitation is one of the items included in this JSR's 
scope.  Below is my strawman proposal to alleviate this issue.

The proposal is to support syntactic sugar for the existing pattern 
along with enhanced API support for retrieving the repeated values.  The 
assumption of at most one value per annotation type is throughly baked 
into the annotations design and the design of the APIs reading 
annotations.  It is impractical to change that decision now; attempting 
to do so would expose the numerous corner cases and interactions the JSR 
175 design avoided.

First, a new meta-annotation is introduced to allow an annotation type 
to declare what its containing type should be:

@interface Container {
  Class<? extends Annotation> value();

so that the declaration

@interface MyAnnotation()

would allow something like

@MyAnnotatio(1) @MyAnnotation(2) @MyAnnotation(3)
public class Foo();

to be treated as

public class Foo();

(I'm not sure what the exact syntactic sugar should be; it might be 
beneficial to wrap the repeated annotations in "@{", "}" to emphasize 
the grouping or to restrict the repeated annotations to be sequentially 

Declaring the container in the annotation type provides the compiler and 
the runtime the information needed to construct or lookup the containing 
type.  There could be a new method on AnnotatedElement like

<T extends Annotation> T[] getRepeatedAnnotation(Class<T> annotationClass)


<T extends Annotation> List<T> getRepeatedAnnotation(Class<T> 

This method could potentially handle some of the tricky cases like 
returning the non-contained annotation if there is one, otherwise return 
the contained annotation, etc.

The intention is to allow the @Container meta-annotation to be 
retrofitted to existing wrapper annotations.



More information about the JSR308 mailing list