How can serialisation/deserialisation break immutability?

后端 未结 7 637
小鲜肉
小鲜肉 2021-02-07 15:54

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

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-07 16:15

    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.

提交回复
热议问题