Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 16 Annotation ElementType.RECORD_COMPONENT cannot be reflected

Using JDK 16, I declared two annotations:

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

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

And I declared a record class like this:

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

Then I use reflection to fetch the annotations of id, which is:

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

But the size of annotations is one and I only got @B, why is that? Thanks

like image 337
Hash Jang Avatar asked May 08 '26 02:05

Hash Jang


1 Answers

Annotations on record components are propagated to potentially four places in the classfile:

  • fields
  • accessor methods
  • constructor arguments
  • record components themselves.

These are gated by whether the annotation is applicable to

  • FIELD
  • METHOD
  • PARAMETER
  • RECORD_COMPONENT

it will be propagated to all the places it is applicable. If it is not applicable to any of these, it is rejected at compile time.

like image 196
Brian Goetz Avatar answered May 10 '26 15:05

Brian Goetz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!