1
votes

Problem for me is to implement clone for an object. This object A has its members object B, which were not created by A. I want to clone A such that only objects created during construction of A to be cloned. The objects which were either passed as reference in A or A's objects or A's object's object not to be cloned. They should only be referenced.

Is this possible? I have gone through some deep cloning libraries source (deep - cloner); it seems they can't make the distinction. I can't do serialization de-serialization as I suspect it will not solve my case. Also the object A that I have to clone is very complex. I involves almost all classes in project. Do the Apache serialization utils takes care of above case?

2

2 Answers

2
votes

It is not possible. Basically, there is nothing in Java that allows you to determine when a given object was created.

The only way you are going to be able to get any traction on this problem is if the object A is able to keep a record of the member objects that it created in its constructor.

1
votes

You will need to manually implement A.clone() so that it clones only the objects you want to be cloned. The default implementation of Object.clone performs a shallow copy operation, so you would need to do something like this:

public class A implements Cloneable {

    [...]
    public Object clone() {
        Object obj = null;

        try {
            obj = super.clone();
            // super.clone performs a "shallow copy" operation.
            // Now you will need to manually clone any objects for
            // which a "deep copy" operation is desired, e.g.
            //
            //    obj.memberX = memberX.clone();
            //    obj.memberY = memberY.clone();
            //    ...
            //
        } catch (CloneNotSupportedException ex) {
            // Should not happen..
        }
        return obj;
    }
}

This assumes that you know which objects you want to have cloned (i.e. which objects where created during construction of A).