Skip to content

Commit 94c767f

Browse files
committed
updated Java 14 Record serialization example
1 parent 4aeb686 commit 94c767f

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

java-14/RecordsSerializationTest.java

+8-3
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,15 @@ private static void read() {
4040
/**
4141
* Records are serialized different from ordinary classes.
4242
* Its fields are written in the same order as declared.
43-
* When it is read, the component constructor as called as normal code would need to do.
43+
* When it is read, the component constructor is called as normal code would need to do.
4444
* It cannot customize its serialization, only the method `writeReplace` can be used to
4545
* create a copy to be serialized.
46-
*
46+
*
4747
* The value of serialVersionUID is fixed to 0L. If we added components to the record,
4848
* it will contain the default value for that type.
4949
* If we change the existing componentes it will throw something like:
5050
* `java.io.InvalidClassException: CustomSerializableRecord; incompatible types for field x`
51-
*
51+
*
5252
* http://cr.openjdk.java.net/~chegar/records/spec/records-serialization.03.html#serialization-of-records
5353
*/
5454
record CustomSerializableRecord(int x, int y) implements Serializable {
@@ -63,6 +63,11 @@ private Object writeReplace() throws ObjectStreamException {
6363
return new CustomSerializableRecord(x + 1, y + 1);
6464
}
6565

66+
private Object readResolve() throws ObjectStreamException {
67+
System.out.printf("Reading from serialized object - x: %s, y: %s\n", x, y);
68+
return new CustomSerializableRecord(x - 1, y - 1);
69+
}
70+
6671
// Won't be called
6772
private void writeObject(ObjectOutputStream out) throws IOException {
6873
System.out.println("Writing object...");

java-16/RecordTest.java renamed to java-16/RecordStaticInnerMemberTest.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
2-
public class RecordTest {
1+
public class RecordStaticInnerMemberTest {
32
public static void main(String[] args) {
43
var outer = new OutterClass();
54
var inner = outer.new InnerClass();

0 commit comments

Comments
 (0)