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.)
Deserialization is implemented by the JVM on a level below the basic language constructs. Specifically, it does not call any constructor.
Both Michael and Stephen gave you an excellent answer, I just want to caution you about
transient
fields.If default value (
null
for references, 0 for primitives ) is not acceptable for them after deserialization then you have to provide your version ofreadObject
and initialize it there.Some nasty black magic happens. There is a backdoor in the JVM that allows an object to be created without invoking any constructor. The fields of the new object are first initialized to their default values (false, 0, null, etc), and then the object deserialization code populates the fields with values from the object stream.
(Now that Java is open sourced, you can read the code that does this ... and weep!)