| Subcribe via RSS

Cloning the unclonable

March 16th, 2010 | No Comments | Posted in Java

Sometimes during development we need to save an object state so that we can latter return to it, due to a problem or a by an user undo request. In these scenarios usually some type of cloning is a good way to go.

Java has a standard way of doing this through the .clone() method, but in order for it to work, the classes need to implement it explicitly. Then comes a day that you need to clone some third party object that does not implement the clone() method, so what do you do?

Me and friend Renato Besen came along an interesting solution during a pair, and I thought it would be fun to share. The object we wanted to clone was Serializable, so we created a class that perform a cloning through serialization, writing the object into memory and then reading it back into another new instance, effectively making a clone of it.

The class is generic, so the final solution is pretty neat, just call:

new SerializationCloner<ThirdPartyClass>().clone(instance);

And that is it! You can get the source from here.

The only obvious downside is performance, so use it with caution.

Tags: , , , ,
  • about me

    I'm Paulo Ragonha, a brazilian hobbyist game developer, who enjoys playing with technology on my free time, my (current) main language is Java so you will probably see a lot of stuff about it in here, I also occasionally talk abut random stuff... and will probably post a "game" every once in a while.
    Thanks for passing by!


  • twitter