i want to clone a given object.
if i do this
public class Something{
Object o; //set in the constructor
public Something(Object o){
this.o = o;}
public Something clone() throws CloneNotSupportedException{
Something temp = super.clone();
if (o instanceof Cloneable) //important part
temp.o = o.clone(); //important part
else temp.o = o;
}
}
this will not work becuase o.clone() is protected.
if i do this instead
if (o instanceof Cloneable) //important part
temp.o = ((Cloneable)o).clone(); //important part
it won't work either because Cloneable is an empty interface.
so how do i convince the compiler that you can clone o?
Alternative would be to use serialization if it's possible to implement Serializable interface. Downside is the performance ofcourse.
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SerializationUtils.html#clone(java.io.Serializable)
If you don't want to use apache commons you could do the same thing using ObjectOutputStream/ObjectInputStream.
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