Reputation: 6881
I need to clone an object I have created (a custom class). Cloning it using the standard object.clone would be messy since it includes references to other objects and it would require me to clone those too.
I read that one way to clone it would be to serialize the object and then de-serialize it.
Is this a good idea?
Upvotes: 1
Views: 1069
Reputation: 30944
You write:
Cloning it using the standard object.clone would be messy since it includes references to other objects and it would require me to clone those too.
When you do the cloning via Serialization you either
In the later case, you can just implement a clone()
method that leaves the other objects out.
Aside for the cost of Serialization, TANSTAAFL
Upvotes: 1
Reputation: 5900
Usually, serialization is used to send objects off somewhere (into a file or over the network) so that somebody else can reconstruct them later. But you can abuse it to reconstruct the object yourself immediately. If the object is serializable at all, then the reconstruction should be a faithful copy.
But this technique is not to be used lightly. First of all, serialization is hugely expensive. It could easily be a hundred times more expensive than the clone() method. Secondly, not all objects are serializable. Thirdly, making a class serializable is tricky and not all classes can be relied on to get it right. (You can assume that system classes are correct, though.) So I believe it's not a good idea.
Upvotes: 0
Reputation: 7388
You need to be aware the serialization adds overhead, a massive overhead compared to direct cloning. You also have to make sure that every member of your class (and in turn every member of every field, ...) needs to be serializable. I would prefer adding a proper clone() implementation.
Upvotes: 1