Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialising and immutable objects

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?

like image 257
Pool Avatar asked Nov 02 '09 19:11

Pool


People also ask

Can immutable class be serialized?

It turns out you can serialize immutable objects because there's no requirement that there be a public no-argument constructor.

Which is an immutable object?

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.

What is immutable with examples?

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.

How can we prevent immutable class from serialization?

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.


1 Answers

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.

like image 142
Tom Hawtin - tackline Avatar answered Nov 02 '22 19:11

Tom Hawtin - tackline