I was reading an article written by an ASF contributor, and he briefly mentioned that an "old Java trick" to deep clone an object is to serialize it and then deserialize it back into another object. When I read this I paused, and thought "hey, that's pretty smart." Unfortunately neither deep cloning, nor serialization, were the subject of the article, and so the author never gave an example of what he was talking about, and online searches haven't pulled back anything along these lines.
I have to assume, we're talking about something that looks like this:
public class Dog implements Serializable
{
// ...
public Dog deepClone()
{
Dog dogClone = null;
try
{
FileOutputStream fout = new FileOutputStream("mydog.dat");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(this);
oos.close();
FileInputStream fin = new FileInputStream("mydog.dat");
ObjectInputStream ois = new ObjectInputStream(fin);
dogClone = (Dog)ois.readObject();
ois.close();
return dogClone;
}
catch(Exception e)
{
// Blah
}
}
Provided that I might be off a little bit (plus or minus a few lines of code), is this a generally-accepted practice for deep cloning an object? Are there any pitfalls or caveats to this method?
Are there synching/concurrency/thread-safety issues not addressed?
Because if this is a best-practices way of deep cloning objects, I'm going to use it religiously.