gpt4 book ai didi

java - 为什么 getAnnotatedParameterTypes 看不到数组类型的注释?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:08:08 27 4
gpt4 key购买 nike

出于某种原因,我不明白为什么这段代码打印出 truefalse,array 有什么特别之处,它不包括此处的注释?

如果您改为使用 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));
}
}

最佳答案

在注解类型@Lel String[]中,注解应用于元素类型String。要注释数组类型,您可以使用 String @Lel []

JLS 在 §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;

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

关于java - 为什么 getAnnotatedParameterTypes 看不到数组类型的注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51086849/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com