Why getAnnotatedParameterTypes does not see annotations for array type?

GotoFinal :

For some reason I don't understand why this code prints true and false, what is special about array that it does not include that annotation here?

It works as expected if you use getParameters instead.

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE, ElementType.PARAMETER})
@interface Lel {
}

class Test {
    public static void a(@Lel String args) {}
    public static void b(@Lel String[] args) {}

    public static void main(String[] args) throws Exception {
        System.out.println(Test.class.getDeclaredMethod("a", String.class)
            .getAnnotatedParameterTypes()[0].isAnnotationPresent(Lel.class));
        System.out.println(Test.class.getDeclaredMethod("b", String[].class)
            .getAnnotatedParameterTypes()[0].isAnnotationPresent(Lel.class));
    }
}
Radiodef :

In the annotated type @Lel String[], the annotation applies to the element type String. To annotate the array type, you would use String @Lel [].

The JLS contains some examples like this in §9.7.4:

Type annotations can apply to an array type or any component type thereof (§10.1). For example, assuming that A, B, and C are annotation types meta-annotated with @Target(ElementType.TYPE_USE), then given the field declaration:

@C int @A [] @B [] f;

@A applies to the array type int[][], @B applies to its component type int[], and @C applies to the element type int. For more examples, see §10.2.

An important property of this syntax is that, in two declarations that differ only in the number of array levels, the annotations to the left of the type refer to the same type. For example, @C applies to the type int in all of the following declarations:

@C int f;
@C int[] f;
@C int[][] f;

Also, getParameters() will work to retrieve the annotation(s) if the way that your annotation is declared allows it to target the parameter declaration itself, as well as the type. JLS §9.7.4 explains in more detail the conditions under which an annotation is determined to target a type, declaration or both.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=466478&siteId=1