org.sonar.l10n.java.rules.squid.S2975.html Maven / Gradle / Ivy
Many consider clone
and Cloneable
broken in Java,
largely because the rules for overriding clone
are tricky and difficult to get right, according to Joshua Bloch:
Object's clone method is very tricky. It's based on field copies, and it's "extra-linguistic."
It creates an object without calling a constructor.
There are no guarantees that it preserves the invariants established by the constructors.
There have been lots of bugs over the years, both in and outside Sun,
stemming from the fact that if you just call super.clone repeatedly up the chain until you have cloned an object,
you have a shallow copy of the object. The clone generally shares state with the object being cloned.
If that state is mutable, you don't have two independent objects.
If you modify one, the other changes as well. And all of a sudden, you get random behavior.
A copy constructor or copy factory should be used instead.
This rule raises an issue when clone
is overridden,
whether or not Cloneable
is implemented.
Noncompliant Code Example
public class MyClass {
// ...
public Object clone() { // Noncompliant
//...
}
}
Compliant Solution
public class MyClass {
// ...
MyClass (MyClass source) {
//...
}
}
See
See Also
- S2157 - "Cloneables" should implement "clone"
- S1182 - Classes that override "clone" should be "Cloneable" and call "super.clone()"
© 2015 - 2025 Weber Informatics LLC | Privacy Policy