Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object cloning with out implementing cloneable interface

Tags:

java

clone

to clone the object do i need to implement 'cloneable' interface. because here my class is a jar file(i mean API). so i can't edit the class. i heard that all classes are extends the base object class and this object class implements cloneable interface. does that mean can we directly clone the object with out implementing the interface. if so in my eclipse i am not getting any option to clone the object. is there any other way to clone the object without implementing the cloneable interface. please explain.

like image 725
ran Avatar asked Nov 19 '11 05:11

ran


2 Answers

It's usually best practice to avoid clone() anyway because it's difficult to do correctly (http://www.javapractices.com/topic/TopicAction.do?Id=71). Perhaps the class in question has a copy constructor?

Alternatively if it implements Serializable or Externalizable, you can deep copy it by writing it to a byte stream and reading it back in

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Object deepCopy = ois.readObject();

(from http://www.jguru.com/faq/view.jsp?EID=20435). This is quick and easy but not pretty... I would generally consider it a last resort.

like image 169
kylewm Avatar answered Oct 18 '22 17:10

kylewm


The Java Object class does not implements the Cloneable interface. It does however have the clone() method. But this method is protected and will throw CloneNotSupportedException if called on an object that does not implement the Cloneable interface. So if you cannot modify the class you want to clone you're out of luck and will have to find another way to copy the instance.

It should be note however that the clone system in Java is full of holes and generally not used anymore. Check out this interview with Josh Bloch from 2002 explaining a few of the issues.

like image 39
orien Avatar answered Oct 18 '22 17:10

orien