It is well-known that Cloneable is broken beyond repair (see the discussion in this question for more information).
Last questions on alternatives and "how do I do it right" are few years old:
- Are there any alternatives to implementing Clone in Java?
- How to properly override clone method?
- Clone() vs Copy constructor- which is recommended in java
- clone() vs copy constructor vs factory method?
- Polymorphic copy in Java
- Proper way to deep copy with copy constructor instead of Object.clone
So I'd like to ask again:
What are the modern day (2014) alternatives to Cloneable?
I am looking for a general-purpose solution. I could imagine the following requirements:
- Some kind of
Copyableinterface which the classes will implement:A extends Copyable. - Deep copying. If an istance of
Areferences an instance ofB,a.copy()should reference a newb.copy(). - Copy to the specified target:
a.copyTo(a1). - Polymorphic copying: if
BextendsAthena.copyTo(b)should copy all the properties ofBfromatob.
Of course I can implement all of this by myself, but wouldn't it be reasonable to have standard interfaces for this? Or am I missing something?
A bit of the background for my context. I'm working a lot with JAXB and schema-derived classes. It is often extremely useful to have deep copying for these classes. Few years ago I wrote a couple of JAXB schema compiler plugins to generate copyTo methods which implement the requirements above (and more). I had to use my own runtime API. Now I was revisiting the case and decided to ask if there's a standard solution.