Clone Android object using serialization
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?
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.
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
- need to serialize those other objects too (otherwise the resulting object is no real clone)
- accept that the clone will be partial (without referenced objects).
In the later case, you can just implement a clone()
method that leaves the other objects out.
Aside for the cost of Serialization, TANSTAAFL
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.
精彩评论