I think the previous green answer was bad , why you might ask?
- It adds a lot of code
- It requires you to list all fields to be copied and do this
- This will not work for Lists when using clone()
(This is what clone() for HashMap says: Returns a shallow copy of this HashMap instance: the keys and valuesthemselves are not cloned.) so you end up doing it manually (this makes me cry)
Oh and by the way serialization is also bad, you might have to add Serializable all over the place (this also makes me cry).
So what is the solution:
Java Deep-Cloning library
The cloning library is a small, open source (apache licence) java library which deep-clones objects. The objects don't have to implement the Cloneable interface. Effectivelly, this library can clone ANY java objects. It can be used i.e. in cache implementations if you don't want the cached object to be modified or whenever you want to create a deep copy of objects.
Cloner cloner=new Cloner();
XX clone = cloner.deepClone(someObjectOfTypeXX);
Check it out at https://github.com/kostaskougios/cloning
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…