Type Annotations in the language model API

Alex Buckley alex.buckley at oracle.com
Fri Feb 15 12:51:40 PST 2013


Previously [1], we proposed to represent type annotations in the 
language model API via an AnnotatedTypeMirror hierarchy that parallels 
the TypeMirror hierarchy. This proposal was driven by an abundance of 
caution for language model implementations that share TypeMirror objects 
across different use sites, such as a single TypeMirror object for both 
uses of String in "@Foo String f1; @Bar String f2;". In addition, we 
proposed new methods on {Type,Variable,Executable}Element to expose 
AnnotatedTypeMirror objects.

We now think our proposal was excessively concerned about freedom for 
implementers of the language model API, rather than keeping a simple 
conceptual model for users of the API.

In keeping with how the Java language now supports annotations on both 
declarations and type uses, we propose to expose annotations uniformly 
on javax.lang.model.element.Element (declarations) and 
javax.lang.model.type.TypeMirror (type uses).

To this end, we propose to pull the annotation methods of Element into a 
new interface which is implemented by both Element and TypeMirror:

package javax.lang.model;
interface AnnotatedConstruct {
   <A extends Annotation> A         getAnnotation(Class<A>);
   <A extends Annotation> A[]       getAnnotationsByType(Class<A>)
   List<? extends AnnotationMirror> getAnnotationMirrors();

(getAnnotationsByType is a new method for repeating annotations, 
discussed on the enhanced-metadata-spec-discuss list.)

The implication for implementers is that a TypeMirror object cannot 
_always_ be shared across multiple uses of a type in 
class/interface/field/method/ctor declarations. Previously, a TypeMirror 
object could _always_ be shared in this manner.

For example, suppose v1 is the VariableElement for the field "@Foo 
String f1;" and v2 is the VariableElement for the field "@Bar String 
f2;". In Java SE 8, v1.asType() must not return the same TypeMirror 
object as v2.asType(). But suppose v3 is the VariableElement for "@Quux 
String f3;" and v4 is the VariableElement for "@Quux String f4;". 
v3.AsType() may return the same TypeMirror object as v4.asType().

Essentially, the concept which TypeMirror has always represented - "type 
in the Java programming language" - is now expanded to "potentially 
annotated type in the Java programming language".

For compatibility, the utility methods for type comparison in 
javax.lang.model.util.Types should ignore annotations. New methods can 
be added, but comparing annotations may be a rathole, so please let's 
use a new thread for utility methods.

We don't propose to revisit type annotations in the core reflection API. 
There, we need new methods exposing a new AnnotatedType hierarchy 
because the legacy Type hierarchy is truly limited to declarations, both 
in concept and in implementation.



More information about the type-annotations-spec-experts mailing list