Annotations on Records and Record Components

Alex Buckley alex.buckley at
Tue Jan 28 17:55:09 UTC 2020

If your true goal is to obtain the names of record components via 
reflection, then you will want to know that the parameter names of the 
canonical constructor are persisted in the class file. These parameter 
names match the component names. (javac enforces this in 14, and the 
spec will mandate it in 15, per JDK-8236599.)

You obtain the parameter names by first obtaining the right Constructor 
object (call Class::getConstructor with the record components' types), 
and then obtaining its Parameter objects (call Executable::getParameters).

I understand that the parameter names are available even if 
`-parameters` is not passed to javac. The rationale is that the record 
component names are the fixed and public protocol of the record, so the 
usual objection to carrying parameter names in the class file -- that 
they form an unintended compatibility surface -- is not relevant.


On 1/28/2020 7:13 AM, Summers Pittman ℝ wrote:
> I created a record but I can't access the annotations on the record
> components.
> Given the following record
> ```java
> record Record(@JsonProperty("id") int id, @JsonProperty("text")  String
> text){ }
> ```
> I ran the following code to reflect the annotations
> ```java
>          var recClass = Record.class;
>          for (RecordComponent recordComponent :
> recClass.getRecordComponents()) {
>              System.out.print("RecordComponent : ");
>              System.out.println(recordComponent.toString());
>              for (Annotation anno :
> recordComponent.getDeclaredAnnotations()) {
>                  System.out.print("RecordComponent Annotation : ");
>                  System.out.println(anno);
>              }
>          }
> ```
> and I don't see the annotations listed in the output:
> ```txt
> RecordComponent : int id
> RecordComponent : java.lang.String text
> ```
> Am I holding it wrong? I'm using Java 14.ea.33 if the version helps.

More information about the amber-dev mailing list