Type-variable parameter with type annotation.

Antonio Cortes Perez antoniocortes at google.com
Mon Jun 17 17:54:15 UTC 2019


I am not able to retrieve the annotation from the parameter param or its
type in the following program when using the javac API (JDK 1.8.0_212).

=== InputFile.java ===
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target({ ElementType.TYPE_USE, ElementType.TYPE_PARAMETER })
@interface TypeAnnotation {

public class InputFile<T> {
  void test(@TypeAnnotation T param) {}
=== end ===

This is a sample program that uses the javac API.

=== JavacTest.java ===
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.TreePathScanner;
import com.sun.source.util.Trees;
import java.io.IOException;
import java.util.Arrays;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.type.TypeMirror;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class JavacTest {

  public static void main(String[] args) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager =
compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> units =
    JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null,
null, null, units);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    new Visitor(Trees.instance(task)).scan(asts.iterator().next(), null);

  private static class Visitor extends TreePathScanner<Void, Void> {

    Trees trees;

    Visitor(Trees trees) {
      this.trees = trees;

    public Void visitVariable(VariableTree node, Void aVoid) {
      TypeMirror type = trees.getTypeMirror(getCurrentPath());
      for (AnnotationMirror annotation : type.getAnnotationMirrors()) {
      return null;
=== end ===

The program does not print anything when using JDK 1.8.

$ javac -cp /path/to/java/home/tools.jar JavacTest.java
$ java -cp .:/path/to/java/home/tools.jar JavacTest InputFile.java

Using JDK 9 produces the expected output.

$ javac JavacTest.java
$ java JavacTest InputFile.java

I also inspected the element, but I did not find the annotation.
      Element element = trees.getElement(getCurrentPath());
      Set<Modifier> modifiers = element.getModifiers();
      List<? extends AnnotationMirror> annotations =

I noticed that the list metadata.type_attributes in the underlying
VarSymbol contains the annotation. But I did not find a way to retrieve it
via the public API. Any tips are appreciated.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/compiler-dev/attachments/20190617/ebcd4710/attachment.html>

More information about the compiler-dev mailing list