How do I make defensive copy of an object?

北战南征 提交于 2019-12-01 09:09:09

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

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.

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