object cloning with out implementing cloneable interface
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.
Their is a api which clone the object without implementing the cloneable interface.
Try this
https://github.com/kostaskougios/cloning
Also you can find more details about cloning objects here
http://javatechniques.com/blog/faster-deep-copies-of-java-objects/
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.