Java16 注释ElementType.RECORD_COMPONENT无法反映

Java 16 Annotation ElementType.RECORD_COMPONENT cannot be reflected

使用JDK16,我声明了两个注解:

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

@Target({ ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface B {}

然后我这样声明了一条记录class:

public record User(@A @B long id, String name, int age) {}

然后我用反射来获取id的注解,即:

Annotation[] annotations = fields[0].getAnnotations();

但是annotations的大小是1,我只得到了@B,这是为什么呢?谢谢

记录组件上的注释可能传播到类文件中的四个位置:

  • 字段
  • 访问器方法
  • 构造函数参数
  • 记录组件本身。

这些取决于注释是否适用于

  • FIELD
  • METHOD
  • PARAMETER
  • RECORD_COMPONENT

它将传播到所有适用的地方。如果不适用于其中任何一个,则在编译时将被拒绝。