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
Annotations on record components are propagated to potentially four places in the classfile:
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.