Shallow Clone

A typical way of cloning an object is to use super.clone() to shallow-clone it, then modifying/cloning any members to create a complete clone.

Extra care must be taken if the original contains members that reference back to itself, e.g.


public class Model implements Cloneable {
  private PropertyChangeSupport support;
  private String name;

  public Model(String name) {
    support= new PropertyChangeSupport(this);
    this.name = name;
  }

  public void setName(String newName) {
    String oldName = this.name;
    this.name = newName;
    support.firePropertyChange("name", oldName, this.name);
  }
}

When this object is cloned the support member variable still references the original object (due to Object’s direct member assignment), thus the listeners would receive a wrong reference.

To fix this, implement a custom clone() method to take care of it. Make sure a new instance is created for it. If you simply change the reference inside the PropertyChangeSupport object, it will screw up the original object instead.


  public Object clone() {
    Model clonedModel = (Model)super.clone();
    clonedModel.support = new PropertyChangeSupport(clonedModel);
    return clonedModel;
  }

Leave a Reply