95. Invoking the canonical constructor via reflection
It is not a daily task to invoke the canonical constructor of a Java record via reflection. However, this can be accomplished quite easily starting with JDK 16, which provides in java.lang.Class
the RecordComponent[] getRecordComponents()
method. As its name and signature suggest, this method returns an array of java.lang.reflect.RecordComponent
representing the components of the current Java record.
Having this array of components, we can call the well-known getDeclaredConstructor()
method to identify the constructor that gets as arguments exactly this array of components. And that is the canonical constructor.
The code that puts these statements into practice is provided by the Java documentation itself, so there is no need to reinvent it. Here it is:
// this method is from the official documentation of JDK
// https://docs.oracle.com/en/java/javase/19/docs/api/
// java.base/java/lang/Class.html#getRecordComponents...