Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i convince the compiler an Object is cloneable (java)?

Tags:

java

cloneable

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?

like image 858
user2999815 Avatar asked Jun 21 '15 11:06

user2999815


1 Answers

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.

like image 132
Dev Blanked Avatar answered Oct 01 '22 11:10

Dev Blanked