Expose Record accessors / canonical constructor?

Johannes Kuhn info at j-kuhn.de
Fri Jun 19 15:04:52 UTC 2020


Recently I dabbed into a few binding APIs, to see how they can work with 
records, and to better understand their challenges.
(For me, binding is creating a mapping between a structural 
representation and nominal representation.)

One particular thing I found was that you usually have to open the 
package that contains the record to the binding library.
This is a task where the IDE won't help with. To illustrate, I basically 
want to write the following:

     record Person(String first, String last) {}
     List<Person> persons = db.query("SELECT first, last FROM persons", 
Person::new);

The problem with the lambda is: what is it's target?
So the next best thing is to pass Person.class.

As Person is a local record, a framework can't directly call the 
canonical constructor or the accessors, instead it has to call 
setAccessible.
This makes a record less like a "just the data, and only the data" and 
more a "the data if you have access to the record".

Is my assumption that frameworks should be able to construct and 
deconstruct arbitrary records correct?
If so, what options do they have?
And what else can the JDK do to support that?

The "obvious" solution is to expose them via MethodHandles.
Finding the canonical constructor is... not very efficient currently:

recordClass.getConstructor(Arrays.stream(recordClass.getRecordComponents())
.map(RecordComponent::getType).toArray(Class<?>[]::new));

This means that every framework has to cache the result (See 
JDK-8247532[1] for example).
Caching them in j.l.Class might help with that.

An other solution is to have a new modifier that explicitly allows 
reflective access.
That is a bigger change, and the question stands what frameworks should 
do in the mean time.

But maybe I'm just tring to fit records into something it was not 
designed for.

- Johannes

[1]: https://bugs.openjdk.java.net/browse/JDK-8247532



More information about the amber-dev mailing list