How can serialisation/deserialisation break immutability?

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

    You can prevent from serialization or cloning with the help of SecurityManager in java

    public final class ImmutableBean {
    private final String name;
    
    public ImmutableBean(String name) {
        this.name = name;
        //this line prevent it form serialization and reflection
        System.setSecurityManager(new SecurityManager());
    }
    
    public String getName() {
        return name;
    }
    

    }

提交回复
热议问题