type annotations on generic method return type

Markus Keller markus_keller at ch.ibm.com
Thu Feb 6 08:58:56 PST 2014


java-se-8-jls-fr-diffs.pdf "9.7.4 Where Annotations May Appear" reads:
"It is possible for an annotation to appear at a syntactic location in a 
program where it could plausibly apply to a declaration, or a type, or 
both."

And later concerning type annotations: "[...] the annotation is deemed to 
apply only to the type which is closest to the annotation."

What about a generic method declaration, where a type parameter 
declaration "<T>" separates the method modifiers from the return type's 
type annotations?

    public @A <T> @B Set<T> foo(T t) { /*...*/ } 

=> If @A is a TYPE_USE annotation, is it also considered a type annotation 
in this case? Although its syntactic location does _not_ make it apply to 
the return type?

=> @B is _not_ syntactically legal according to the current grammar, since 
Result cannot start with an annotation:

MethodHeader:
        {MethodModifier} [TypeParameters] Result MethodDeclarator [Throws]

Result:
        UnannType
        void

Both javac and ecj currently accept the above declaration.


BTW: Note that term "closest" in "the type which is closest to the 
annotation" is not defined by the spec. Likewise, type annotations on 
array types are only defined in an informal section.
"Closest" seems to mean something like "the next following type reference 
that is not in an other annotation (and not in a type parameter 
declaration)".

Regards,
Markus



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