开发者

How can I copy an object in Java?

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


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.


Try the Java deep cloning library

Cloner cloner = new Cloner();
cloner.deepClone(object);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜