Reader small image

You're reading from  Java Coding Problems - Second Edition

Product typeBook
Published inMar 2024
PublisherPackt
ISBN-139781837633944
Edition2nd Edition
Right arrow
Author (1)
Anghel Leonard
Anghel Leonard
author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard

Right arrow

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...
lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Java Coding Problems - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781837633944

Author (1)

author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard