Deserialization of records doesn't work in Java15
reuschling opened this issue · comments
If you want to deserialize a record, you get an IllegalAccessException: Can not set final ... field
.
I assume the problem will exist also in the new Java16 which comes out next week, where records won't be a preview feature anymore.
Example code:
public static record TestRecord(String str, boolean bool)
{
}
...
TestRecord rec = new TestRecord("check", false);
String strJson = JsonWriter.objectToJson(rec);
System.out.println(strJson);
TestRecord clone = (TestRecord) JsonReader.jsonToJava(strJson);
System.out.println(clone);
Gson also has this issue: google/gson#1794. According this, the solution would be to use the constructor in favour of setting the final fields via reflection.
json-io has the assign instantiator customization that lets you write the code that creates the object, which allows you to set up the object in regular code - your code is called when the troubled class is encountered. This is dicussed in the user-guide, linked here: https://github.com/jdereg/json-io/blob/master/user-guide.md under the Customization section. Also, recent changes have been added to support JDK's through 17.