Once upon a time there was a class:
public class Scope<C extends Cloneable & Comparable<C>> implements Comparable<Scope<C>>, Cloneable, Serializable {
private C starts;
private C ends;
...
@SuppressWarnings("unchecked")
@Override
public Object clone() {
Scope<C> scope;
try {
scope = (Scope<C>) super.clone();
scope.setStarts((C) starts.clone()); // The method clone() from the type Object is not visible
scope.setEnds((C) ends.clone()); // The method clone() from the type Object is not visible
} catch (CloneNotSupportedException e) {
throw new RuntimeException("Clone not supported");
}
return scope;
}
}
In Object we have:
protected native Object clone() throws CloneNotSupportedException;
And Cloneable interface is:
public interface Cloneable {
}
How should I clone this?
This is one reason why no one likes Cloneable
. It's supposed to be a marker interface, but it's basically useless because you can't clone an arbitrary Cloneable
object without reflection.
Pretty much the only way to do this is to create your own interface with a public clone()
method (it doesn't have to be called "clone()
"). Here's an example from another StackOverflow question.
Use the Java Deep-Cloning library.
The cloning library is a small, open source (apache licence) java library which deep-clones objects. The objects don't have to implement the Cloneable interface. Effectivelly, this library can clone ANY java objects. It can be used i.e. in cache implementations if you don't want the cached object to be modified or whenever you want to create a deep copy of objects.
Cloner cloner=new Cloner();
XX clone = cloner.deepClone(someObjectOfTypeXX);
A previous answer had the following drawbacks:
clone()
; the clone()
for HashMap
notes: Returns a shallow copy of this HashMap
instance: the keys and values themselves are not cloned, so you end up doing it manually.Serialization is also bad because it may require adding Serializable
everywhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With