How can serialisation/deserialisation break immutability?

后端 未结 7 650
小鲜肉
小鲜肉 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:00

    The dirt-simple answer is

    class X implements Serializable {
        private final transient String foo = "foo";
    }
    

    The field foo will equals "foo" if the object is newly created, but will be null when deserialized (and without resorting to dirty tricks, you won't be able to assign it).

提交回复
热议问题