[type-annos-observers] Are annotations on parameter types supported in lambda expressions?

Alex Buckley alex.buckley at oracle.com
Mon Mar 17 19:48:14 UTC 2014


Hi Dieter,

On 3/15/2014 4:57 AM, Dieter Kleinrath wrote:
> I'm not sure, if this is the right place to ask this question, or if it
> would be better to ask the developers of JSR 335 (Project Lambda).

type-annotations-spec-comments is the right place to ask about the 
design intent of type annotations.

> The JSR 308 Specification is not very specific about whether Type
> Annotations should also be allowed on the type parameters of lambda
> expressions or not. But if I read it correctly, I guess code like the
> following should be ok (where MyTypeAnnotation is an Annotation
> with ElementType#TYPE_USE):
>
> Consumer<String> c = (@MyTypeAnnotation String p) -> System.out.println(p);

You speak of "type parameters of lambda expressions" but lambda 
expressions are not generic so they cannot declare type parameters. As 
to the types of formal parameters of lambda expressions, it has been 
legal to annotate them for some time [1]. See JLS8 9.6.4.1, 9.7.4, and 4.11.

[1] 
http://mail.openjdk.java.net/pipermail/type-annotations-spec-experts/2012-December/000044.html

> But the current JDK 8 (b132) javac compiler does not store the information
> of parameter type annotations in the generated class files (the same is
> true for the current Eclipse JDT compiler). I tested this by trying to get
> the Annotation at runtime with Method#getAnnotatedParameterTypes() and by
> reading the class file with the latest ASM build (that already supports
> Type Annotations).

javac emits the correct Runtime[In]VisibleTypeAnnotations attribute for 
annotations on the types of formal parameters of a lambda expression. 
The attribute appears on the private method generated for a lambda 
expression, so you need to run javap with -p to see it.

However, there are known bugs in the emission of, and especially the 
reflection of, annotations on types of formal parameters. See 
https://bugs.openjdk.java.net/browse/JDK-8027181.

> PS.: On a side note: parameter names of lambda expressions are currently
> also not stored in the class files, if one compiles with javac
> -parameters...

I confirm this is a javac bug; thanks, I'll report it.

Alex


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