You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

Calling overridable methods from the clone() method is dangerous for two reasons. First, a malicious subclass may override the method and affect the behavior of the clone() method. Second, a trusted subclass may observe the object in an uninitialized state because its construction may not have concluded.

Noncompliant Code Example

class BadClone {
  HttpCookie[] cookies = new HttpCookie[20];
  public Object clone() throws CloneNotSupportedException {		
    final BadClone clone = (BadClone) super.clone();
    clone.deepCopy();
    return clone;
  }
  
  public void deepCopy() {
    if (cookies == null) {
      throw new NullPointerException();
    }
     
    // deep copy
    HttpCookie[] cookiesCopy = new HttpCookie[cookies.length];

    for (int i = 0; i < cookies.length; i++) {
      // manually create copy of each element in array
      cookiesCopy[i] = (HttpCookie) cookies[i].clone();
    }
  }
}

Compliant Solution


  • No labels