Niraj Patel Niraj Patel -4 years ago 85
Java Question

Deep Cloning in Java - Cloning only objects that are being constructed

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download