I have an class defining an immutable value type that I now need to serialize. The immutability comes from the final fields which are set in the constructor. I've tried serializing, and it works (surprisingly?) - but I've no idea how.
Here's an example of the class
public class MyValueType implements Serializable { private final int value; private transient int derivedValue; public MyValueType(int value) { this.value = value; this.derivedValue = derivedValue(value); } // getters etc... }
Given that the class doesn't have a no arg constructor, how can it be instantiated and the final field set?
(An aside - I noticed this class particularly because IDEA wasn't generating a "no serialVersionUID" inspection warning for this class, yet successfully generated warnings for other classes that I've just made serializable.)
By implementing Serializable the BusinessCard class can already be serialized. To illustrated the problem with final fields we will implement the serialization and deserialization methods writeObject() and readObject() by hand. Serializing the data of our BusinessCard class is straightforward.
The deserialization process does not use the object's constructor - the object is instantiated without a constructor and initialized using the serialized instance data.
transient and final : final variables are directly serialized by their values, so there is no use/impact of declaring final variable as transient.
Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. The byte stream created is platform independent.
Deserialization is implemented by the JVM on a level below the basic language constructs. Specifically, it does not call any constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With