Search code examples
javaserializationfinal

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?


Solution

  • In the typical serialization case, it is not required that class have an empty constructor or non-final fields to be serializable.

    Now, if you have to do your own serialization, or you need to subclass a class that doesn't implement Serializable, that is a different story.

    So you need to provide some more details of how you are having a problem.