Search code examples
javareflectionjava-recordjava-16

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


Solution

  • 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.