I am deep-cloning a big Java class using serialization, as suggested by this answer. In the corresponding question I explained why I need to clone in this way, and that highlights an important difference in the results of different deep-cloning techniques, about preserving shared references in the clone, which in my case is a must. In a few words if in the original two fields point to the same object, in the deep clone those fields should not point to two different new objects but to the same new object. Deep cloning through serialization achieves this.
Since the only change to the classes in the tree that is required by this technique is to have all the classes implement Serializable
, I am not writing a "clone" method in each class of the tree. So I am not writing in each class the code to clone each of its fields. But I still want to exclude some of the fields from the cloning process, and I do that by adding the transient
modifier to the declaration of the fields that I don't want to clone. Those fields will be null
in the clone.
Now I have a different need. I need to be able to say that a certain field does have to be cloned, but not deep-cloned: just copy the reference; let that field in the clone point to the same object as in the original.
So I am wondering how to make so that serialization will clone that particular field by simply copying the reference instead of serializing - deserializing it like it does with the other fields. This is my question.
Otherwise the only solution I can think of is to implement a "clone" method (not necessarily Object.clone()
) in each class of the tree, and in each "clone" method assign each field explicitly, using serialization for some fields and copying the reference for other fields. But in addition to this being a lot of work due to the class to clone having lots of fields, I'm also afraid that in this way I will no longer be preserving the shared references within the tree of the main object, because I would be cloning each field separately, so if two fields in the tree point to the same object this fact will not be known while cloning each of these fields, so it won't be possible for serialization to make them point to the same new object.