I need to implement a deep clone in one of my objects which has no superclass.
What is the best way to handle the checked
public MyObject clone()
foo = (MyObject) super.clone();
catch (CloneNotSupportedException e)
throw new Error();
// Deep clone member fields here
Do you absolutely have to use
clone? Most people agree that Java's
clone is broken.
If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think
cloneis deeply broken. [...] It's a shame that
Cloneableis broken, but it happens.
You may read more discussion on the topic in his book Effective Java 2nd Edition, Item 11: Override
clone judiciously. He recommends instead to use a copy constructor or copy factory.
He went on to write pages of pages on how, if you feel you must, you should implement
clone. But he closed with this:
Is all this complexities really necessary? Rarely. If you extend a class that implements
Cloneable, you have little choice but to implement a well-behaved
clonemethod. Otherwise, you are better off providing alternative means of object copying, or simply not providing the capability.
The emphasis was his, not mine.
Since you made it clear that you have little choice but to implement
clone, here's what you can do in this case: make sure that
MyObject extends java.lang.Object implements java.lang.Cloneable. If that's the case, then you can guarantee that you will NEVER catch a
AssertionError as some have suggested seems reasonable, but you can also add a comment that explains why the catch block will never be entered in this particular case.
Alternatively, as others have also suggested, you can perhaps implement
clone without calling