Java 14 records canonical constructor
Christian Beikov
christian.beikov at gmail.com
Thu Jun 4 19:31:01 UTC 2020
Am 04.06.2020 um 21:06 schrieb Remi Forax:
>> This could be done through a static factory method as well.
>>
>> public record UserRecord(String userName, List<String> mailAddresses) {
>> public static UserRecord create(String userName, List<String>
>> mailAddresses) {
>> return new UserRecord(userName, List.copyOf(mailAddresses));
>> }
>> }
>>
> Nope, because serialization is based on the canonical constructor.
>
> Rémi
Not sure I understand the serialization argument. Can't you define a
readResolve method for that purpose if you really want to ensure it uses
a defensive copy for deserialization? Like this:
public record UserRecord(String userName, List<String> mailAddresses) {
public static UserRecord create(String userName, List<String>
mailAddresses) {
return new UserRecord(userName, List.copyOf(mailAddresses));
}
private Object readResolve() {
return create(userName, mailAddresses);
}
}
Maybe the "compact named constructor" I mentioned before could be used
to generate the static create method and the readResolve method?
public record UserRecord(String userName, List<String> mailAddresses) {
public UserRecord create {
mailAddresses = List.copyOf(mailAddresses);
}
}
Sorry if this is going to far. I'm just looking for a way to ensure that
a record is really composed of just the record components such that the
canonical constructor can't alter anything to avoid accidental bugs. If
you say it's the programmers responsibility to ensure this, I'm fine
with that. I'd be curious to know what you want to utilize this property
of records for though :)
More information about the amber-dev
mailing list