How do I make defensive copy of an object?

偶尔善良 提交于 2019-12-04 01:46:56

问题


How do I make defensive copies of a Mutable Object which contains a mutable field in an Immutable Object?

class ImmutableObject {

  private final MutableObject immutable_field;

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

class MutableObject {

  public int mutable_field;
}
  • The MutableObject does not have a constructor that lets me set the field.
  • The MutableObject's current state should be captured in the Immutable Object and never changed.

回答1:


What you need to do is in

  MutableObject return_immutable_field() {
    return immutable_field;
  }

Change to:

  MutableObject return_immutable_field() {
    MutableObject tmp = new MutableObject();
    tmp.mutable_field = immutable_field.mutable_field;
    return tmp;
  }

For an explanation see http://www.javapractices.com/topic/TopicAction.do?Id=15




回答2:


Well, assuming that there is nothing to be done about the declaration of the mutable object class, one could leverage reflection (Class.newIntance() and Class.getFields()) to create a new object and copy field values. You could also implement deep copying in this manner. If the class supports serialization, then another hackish approach would be to serialize the object and then save a deserialized copy. If it is possible to fix the design of the mutable object, though, that would be a better approach.

Edit
For the particular example that you've given, Romain's answer does what you want. If you have a general mutable object that doesn't provide a mechanism for copying it and for which the type may not be known until later, then the reflection approach is how one would implement a copy mechanism.



来源:https://stackoverflow.com/questions/2954791/how-do-i-make-defensive-copy-of-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!