I was asked this question in an interview. The interviewer wanted to know how to make an object immutable. and then he asked what if I serialise this object - will it break immu
When you serialize an object graph that has multiple references to the same object, the serializer notes this fact, so that the deserialized object graph has the same structure.
For example,
int[] none = new int[0];
int[][] twoArrays = new int[] { none, none };
System.out.print(twoArrays[0] == twoArrays[1]);
will print true
, and if you serialized and deserialized twoArrays
then you would get the same result instead of each element of the array being a different object as in
int[][] twoDistinctArrays = new int[] { new int[0], new int[0] };
You can exploit this support for reference sharing to craft bytes after a serialized entry to share a reference with a privately help object or array, and then mutate it.
So an unserializable class can maintain invariants -- that a privately held object does not escape -- that a serializable class cannot maintain.