Record Class Reflection in Java

Record Classes
Record classes are a special type of class for building a record. You have the same methods available that you would have on non-record classes. There are methods specific to working with reflection with record types that make it much easier and are what this article will be focusing on. The examples will use the following record class.
package press.bytesize;
public record User(int id, String name) {
}
You can check to see if a class is a record class using the isRecord() method. This returns true if a class is a record and false if it isn't.
final boolean isRecord = User.class.isRecord();
Fields
Instance fields aren't supported in record classes. Fields are created based on each of the components in a record signature and are the same name that is in the signature. You can get an array of these fields using the getDeclaredField() method.
final Field[] fields = User.class.getDeclaredFields();
You can also get an individual field by its name using the getDeclaredField(String) method.
final Field field = User.class.getDeclaredField("id");
The RecordComponent Class
The RecordComponent class is a class used specifically for record classes. You can get an array of each of the RecordComponents using the getRecordComponents() method. This method will return null if the class isn't a record class and an empty array if it is a record without any components.
Component Name
A component name is the name defined in the record class signature. This name matches both the instance variable created as well as the accessor method name. You can get the name using the getName() method.
for (final RecordComponent c : User.class.getRecordComponents()) {
System.out.println(c.getName());
}
This will print the following:
id
name
Component Type
You can get the type of a component using the getType() method. This returns a Class for the type it was defined as.
for (final RecordComponent c : User.class.getRecordComponents()) {
final Class<?> type = c.getType();
// ...
}
Accessor Method
Normally you will use the getDeclaredMethod(String) to get a Method class. You can still do this, but with a RecordComponent it has an accessor() method that returns the Method class.
for (final RecordComponent c : User.class.getRecordComponents()) {
final Method method = c.accessor();
}
Conclusion
A record class is just a class. Because of this, you can use the traditional methods that are used with class reflection. The getRecordComponents() method was introduced to make it easier to work with record class reflection.