posted 21 years ago
the previous post about it being a shallow copy is exactly correct. 99 times out of 100 when I want to use someObject.clone() I **DO** want a deep copy. So far, the easiest technique I've developed to do this is as follows: (1) make sure that all my objects are Serializable. (2) override the clone() method using Data[Input,Output]Stream objects to serialize/deserialize the object. That will always return a deep copy and I don't have to worry about screwing up the .clone() method if I add/remove properites of the object. Here's my clone() method:<br><br>
<xmp>
/**
* create a deep copy of this object by serializing it to
* a byte stream and then de-serializing it.
*/
public Object clone()
{
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
oos.flush();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Object o = ois.readObject();
bais.close();
ois.close();
baos.close();
oos.close();
return o;
} catch (Exception e) {
throw new RuntimeException(e.toString());
}
}
</xmp>
Java EE Evangelist — Author, EJB 3 in Action 2nd Edition — Java Community Process Member