tags:

views:

97

answers:

2

Hi there,

I've searched around, and saw some tips, but still couldn't find the solution to my problem in hand: I need to FAITHFULLY copy an existing java object instead of creating a reference to the existing one. I don't have the access to the class, and it implements a clone method through its parent class, which actually creates a reference. I tried to go with "serialization/deserialization" route, it worked to some degrees but the copy is NOT exactly the same as the original one. Can this be done at all? Thanks in advance!

David

+1  A: 

Try the Java deep cloning library

Cloner cloner = new Cloner();
cloner.deepClone(object);
Bozho
this looks interesting as well, if it lives up to its claims. I'll have a look at this library, thanks!
David Zhao
+2  A: 

In the general case, you should not and you cannot.

Why you should not:

There are objects that should not be cloned- esp. those that reference resources outside your software's control- duplicating them could cause chaos.

Why you cannot:

Serialization and deserialization will only work if all the objects referenced by the object being cloned are serializable.

You could write some code that uses reflection to make a deep-clone by instantiating new objects and deep-cloning recursively all the fields, however, try implementing a method which can deep clone this object:

public class Evil {
    public Evil() {
        throw new RuntimeException();
    }
}

The crux of the matter is that, if I'm not mistaken, cloning via reflection invariably depends on invoking constructors via Reflection, and constructors are not guaranteed to work.

However, in most cases, this approach will clone most objects. But you still should not do that! I can't think of a valid scenario for doing this.

edit: also, as some commenters pointed out "faithful copy" is quite ill-defined.

edit 2: conclusion: only a class can know if it should be cloneable and how to do it.

alex