I have a class which is intended for immutable use, hence I would like to label all the fields final
.
However the class is serialized and deserialized to send over the network. For this to work an empty constructor is required. This prevents me creating the final fields.
I'm sure this is a fairly common problem but I can't find a solution. How should I proceed?
It turns out you can serialize immutable objects because there's no requirement that there be a public no-argument constructor.
An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications.
The immutable objects are objects whose value can not be changed after initialization. We can not change anything once the object is created. For example, primitive objects such as int, long, float, double, all legacy classes, Wrapper class, String class, etc. In a nutshell, immutable means unmodified or unchangeable.
If an immutable object was serialized, its raw bytes could be modified so that upon deserialization the object is no longer the same. This can't be prevented completely. Encryption, checksums, and CRC's will help to prevent this though. private is not really required.
A no-arg constructor is not required. The most derived non-serialisable class does need a no-arg constructor available to the least-most derived serialisable class.
If you need to mutate fields inside a readObject
, then use a serial proxy through readResolve
and writeReplace
.
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