[JSR308] javac, com.sun.source.tree and annotation on types

Michael Ernst mernst at csail.mit.edu
Sat Feb 3 11:30:55 EST 2007


Rémi-

Thanks for your perceptive question regarding annotations in ambiguous
locations.

> By example  in
> class Test {
>   @NonNull @Column(name="_NAME") String name;
> }
> 
> Column is an annotation  on name and
> NonNull is an annotation on its type.

Here is another example.  In 

    @Deprecated @NonNull Dimension getSize() { ... }

"@Deprecated" applies to the method and "@NonNull" applies to the
return type.

> It raises some interresting questions :
> Is this separation done by the compiler or by a specific annotation 
> processor ?

When an annotation processor encounters an annotation in this
position, it can treat the annotation as applying to the method or to
the return type, or it can issue a warning/error if the annotation is
not sensible in either location.  (The annotation processor can choose
by using the "@Target" annotation that appears on the Java definitions
of the "Deprecated" and "NonNull" interfaces, or in some other way.)

(An alternate design would have the annotation processing framework,
rather than the annotation processor, use the "@Target" annotation to
disambiguate.)

> suppose an annotation declared using @Target() with two ElementTypes
> one on field and the other on type. Is this legal ?
> Is this annotation will appear in the two groups ?

This is legal, but I'm not sure that it is sensible.
In such a case, the annotation would appear in both groups.

I don't expect that there will be cases that confuse programmers in
practice, but I could be wrong.  This design assumes that there are
few annotations that can apply equally well to both methods and return
value types, and have different semantics in the two situations.  If
such annotations are common, then a different syntax may be warranted.
I would be very interested in examples of such annotations.

                    -Mike



More information about the JSR308 mailing list