Search code examples
javatypesannotations

Type annotation throws 'cannot find symbol' when using a fully qualified type


package com.company;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;

public class Main {

    @Target(ElementType.TYPE_USE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface A {}

    public static void main(String[] args) {
    }

    private List<@A Integer> integers1;

    private List<@A java.lang.Integer> integers2;
}

on private List<@A java.lang.Integer> integers2; I get an error:

Error:(20, 21) java: cannot find symbol symbol: class java
location: class com.company.Main

is it bug in program?


Solution

  • This is apparently a normal behavior (9.7.4):

    A type annotation is admissible if both of the following are true:

    • The simple name to which the annotation is closest is classified as a TypeName, not a PackageName.

    • If the simple name to which the annotation is closest is followed by "." and another TypeName - that is, the annotation appears as @Foo T.U - then U denotes an inner class of T.

    In other words the simple name which @A is closest to (java) is a PackageName so the annotation is inadmissible and a compiler error occurs.

    And the correct syntax for a type annotation on a qualified name is java.lang.@A Integer.