Working with Records
Records are a particular type of class, that strongly enforce non-modifiability. It also introduces the notion of record component. Both elements have an impact on the Reflection API.
Identifying Record Type
When were introduced in Java SE 16, several new methods and classes were added to the Reflection API. Among them is a method on the class Class
to check if a given class is a record class : Class.isRecord()
. You can learn more about records on this page.
Suppose that you have the following record.
You can see this simple method in action on the following example.
Running the previous code prints the following.
Getting Components Information
Records also define a new element for the Java language, which is the record component. A record component is one of the elements declared along with the declaration of a record. The Reflection API also supports this notion of record component.
The Reflection API gets a new class: RecordComponent
that models a component of a record. You have several methods on this class.
Component API | Comments |
---|---|
getDeclaringRecord() |
Returns the class that declares this component |
getAccessor() |
Returns the method that models the accessor of this component |
getName() |
Returns the name of this component. |
getType() |
Returns the type of this component, as a Class object. |
getGenericType() |
Returns the generic type of this component, as a Type object. |
Then you can get the components of a record in an array of type RecordComponent[]
.
Let us see these methods in action.
Running the previous code prints the following.
Accessing Record Fields
Note that there is no method on the RecordComponent
class to get a reference on the Field
object that models the field of this component.
You can still get a reference on the Field
of records using the Class.getDeclaredFields()
method. But you cannot modify the field of a record, even by calling Field.setAccessible(true)
. This behavior is specific to records.
Let us examine the following example. Suppose that you have the following record.
This record has two final instance fields x
and y
, that you can get using the Reflection API.
Running the previous code prints the following.
You can use these fields to read their values, as you can see on the following example.
Note that the x
field is private, reason why you need to call xField.setAccessible(true)
.
The previous example prints the following.
Note that you could have also used xField.getInt(p)
to get the value of x
, to avoid auto-unboxing.
But you cannot use this modify the value of x
. You can try to run the following code.
You will then get the following exception IllegalAccessException
.
Last update: July 25, 2024