Java 14/15 records can not set final field
See original GitHub issueHi, as the following error describes, java records (preview feature) deserialization isn’t working in gson, Jackson is adding support in its very soon release 2.12, is there going to be same support/fix in gson ?
java.lang.AssertionError: AssertionError (GSON 2.8.6): java.lang.IllegalAccessException: Can not set final java.lang.String field JsonGsonRecordTest$Emp.name to java.lang.String
Here’s a sample test
record Emp(String name) {}
@Test
void deserializeEngineer() {
Gson j = new GsonBuilder().setPrettyPrinting().create();
var empJson = """
{
"name": "bob"
}""";
var empObj = j.fromJson(empJson, Emp.class);
}
Issue Analytics
- State:
- Created 3 years ago
- Reactions:30
- Comments:25 (3 by maintainers)
Top Results From Across the Web
Cannot use final fields in Room entity - java - Stack Overflow
I have created a similar class called Record, following the official docs. public class Record { @PrimaryKey(autoGenerate = true) @ColumnInfo( ...
Read more >4 Records - Java - Oracle Help Center
Records cannot declare instance fields (other than the private final fields that correspond to the components of the record component list); any other...
Read more >JDK-8247444 Trust final fields in records - Java Bug Database
No change in Field::setAccessible(true), i.e. it will succeed to allow existing frameworks to have read access to final fields in records (no write...
Read more >Font0 - Rocket Software Documentation
Using Structs for Disconnected Record Sets ... Create a Java Keystore ... Model refers to input field FieldName, which is not found in...
Read more >2 Server Error Message Reference - MySQL :: Developer Zone
Message: Record has changed since last read in table '%s' ... Message: Variable '%s' is a SESSION variable and can't be used with...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Another workaround would be to use a factory so you don’t have to write deserializers for each record.
The problem seems to exist only in Java 15 with preview enabled. Running your test under Java 14 with preview enabled and printing the
empObj
givesEmp[name=bob]
.JDKs used,
This is due to changes in Java 15 that makes final fields in records notmodifiable via reflection. More information can be found here:
The relevant part on handling them going forward:
A current workaround is to write a Deserializers that uses the records constructor instead of reflection.