如何制作对象的防御性副本?

unj*_*nj2 3 java defensive-copy effective-java

如何制作包含不可变对象中可变字段的可变对象的防御性副本?

class ImmutableObject {

  private final MutableObject immutable_field;

  ImmutableObject(MutableObject y) {
    this.immutable_field = y;
  }
}

class MutableObject {

  public int mutable_field;
}
Run Code Online (Sandbox Code Playgroud)
  • MutableObject没有允许我设置字段的构造函数.
  • MutableObject的当前状态应该在Immutable Object中捕获并且永远不会改变.

Rom*_*eau 7

你需要做的是在

  MutableObject return_immutable_field() {
    return immutable_field;
  }
Run Code Online (Sandbox Code Playgroud)

改成:

  MutableObject return_immutable_field() {
    MutableObject tmp = new MutableObject();
    tmp.mutable_field = immutable_field.mutable_field;
    return tmp;
  }
Run Code Online (Sandbox Code Playgroud)

有关说明,请参阅http://www.javapractices.com/topic/TopicAction.do?Id=15