views:

64

answers:

2

Problem for me is to implement clone for an object. This object A has it's members object B, which were not created by A. I want to clone A such that only object's 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) , seems the 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. Does apache serialization utils takes care of above case ?

+1  A: 

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.

Stephen C
+1  A: 

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).

Grodriguez