为什么getAnnotatedParameterTypes没有看到数组类型的注释?

Got*_*nal 6 java reflection annotations

出于某种原因,我不明白为什么这个代码会打印出来,true并且false有关数组的特殊之处是它不包含这个注释吗?

如果您使用它,它会按预期工作getParameters.

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

Rad*_*def 7

在带注释的类型中@Lel String[],注释适用于元素类型String.要注释数组类型,您可以使用String @Lel [].

JLS在§9.7.4中包含了一些这样的例子:

类型注释可以应用于数组类型或其任何组件类型(第10.1节).例如,假设A,BC是注释类型的元注释有@Target(ElementType.TYPE_USE),则给定的字段声明:

@C int @A [] @B [] f;
Run Code Online (Sandbox Code Playgroud)

@A适用于数组类型int[][],@B适用于其组件类型int[],并@C适用于元素类型int.有关更多示例,请参见§10.2.

此语法的一个重要属性是,在两个仅在数组级别数不同的声明中,类型左侧的注释引用相同的类型.例如,@C适用于int以下所有声明中的类型:

@C int f;
@C int[] f;
@C int[][] f;
Run Code Online (Sandbox Code Playgroud)

此外,getParameters()如果声明注释的方式允许它定位参数声明本身以及类型,则可以检索注释.JLS§9.7.4更详细地解释了确定注释以确定类型,声明或两者的目标的条件.