Type-use annotation on var lambda parameter
Tagir Valeev
amaembo at gmail.com
Mon Nov 3 11:32:47 UTC 2025
Hello!
I stumbled on the following issue. Let's consider this Java file:
package com.example;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.function.Function;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(value=RUNTIME)
@Target(value={TYPE_USE})
@interface Anno {
}
public class TestClass {
public static void main(String[] args) {
Function<Integer, String> f = (@Anno var val ) ->
Integer.toHexString(val);
System.out.println(f.apply(10));
}
}
As you can see, there's a TYPE_USE annotation which is applied to the
lambda parameter declared with 'var' keyword. If I understand JLS 9.7.4 [1]
correctly, this should not be legal:
> If the annotation appears before a void method declaration or a variable
declaration that uses var (§14.4, §15.27.1), then there is no closest type.
If the annotation's interface is deemed to apply only to the type which is
closest to the annotation, a compile-time error occurs.
However, javac accepts this code. I tried different versions between Java
11 and Java 25, and the result is the same: the file is compiled
successfully. However, the TestClass.class file contains no references to
the Anno annotation at all, despite it having the RUNTIME retention. So it
looks like the annotation is silently ignored.
One thing that confuses me is that the Eclipse compiler (ecj-4.34.jar) also
accepts this code. However, it generates
a RuntimeVisibleTypeAnnotations attribute for the Anno annotation. So
either both compilers accept this code incorrectly, or my understanding of
the specification is wrong.
Could you please take a look at the javac issue? I'd be happy to be
corrected if I misunderstood the specification. Thank you in advance!
Tagir Valeev
[1] https://docs.oracle.com/javase/specs/jls/se25/html/jls-9.html#jls-9.7.4
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/compiler-dev/attachments/20251103/b23cfbf6/attachment.htm>
More information about the compiler-dev
mailing list