clone() of a class that can be extended does not call super.clone()

tx0/java:clone-without-superrecommendedwarningbug

What it finds

A clone() of a class that is not final and does not call super.clone() creates the copy with new, so a subclass that inherits it gets copies of the wrong class: (Sub) sub.clone() fails with a ClassCastException.

Reported for classes that are not final and implement Cloneable themselves. A call of a method of the class whose name mentions cloning, which may call super.clone() in turn, is taken as doing so.

From the rule's source, clone_without_super.rs.

Example from the rule's tests
class Shape implements Cloneable {  int sides;   @Override  public Shape clone() {tx0 reports: clone() does not call super.clone()    Shape copy = new Shape();    copy.sides = sides;    return copy;  }} final class Square implements Cloneable {  @Override  public Square clone() {    return new Square();  }} class Circle implements Cloneable {  @Override  public Circle clone() {    try {      return (Circle) super.clone();    } catch (CloneNotSupportedException e) {      throw new AssertionError(e);    }  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:clone-without-super" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:clone-without-super] reason="..."

tx0 explain tx0/java:clone-without-super shows the same in the terminal. Found a false positive? Report it.