Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Changed to Applicability and updated a reference to Java 7

...

The Java API for the clone() method [API 20062011] says:

By convention, the returned object should be obtained by calling super.clone. If a class and all of its superclasses (except Object) obey this convention, it will be the case that x.clone().getClass() == x.getClass().

...

Code Block
bgColor#ccccff
class Base implements Cloneable {
  public Object clone() throws CloneNotSupportedException {
    return super.clone();	 
  }
  protected void doLogic() {
    System.out.println("Superclass doLogic");
  }
}

class Derived extends Base {
  public Object clone() throws CloneNotSupportedException {
    return super.clone();
  }
  protected void doLogic() {
    System.out.println("Subclass doLogic");
  }
  public static void main(String[] args) {
    Derived dev = new Derived();
    try {
      Base devClone = (Base)dev.clone(); // has type Derived, as expected
      devClone.doLogic();  // prints "Subclass doLogic", as expected
    } catch (CloneNotSupportedException e) { /* ... */ }
  }
}

...

Applicability

Failing to call super.clone() may result in a cloned object having the wrong type, with resulting unexpected or incorrect results when it is used.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

MET53-JG

medium

probable

low

P12

L1

Automated Detection

Automated detection is straightforward.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

Bibliography

 

MET15-J. Do not use deprecated or obsolete classes or methods      05. Methods (MET)      MET17-J. Do not increase the accessibility of overridden or hidden methods

...