如何复制未知对象?

时间:2014-10-24 09:18:20

标签: java swing serialization io clone

我想知道如何用Java复制对象。但我的意思是复制而不实现clonable接口,但复制已存在的对象,all包含其他对象,例如:

JEditorPane editorOryginal = new JEditorPane();
editorOryginal.addFocusListener(new FocusAdapter() {});
editorOryginal.setText("Hello World!");
// ...... other setter and other listeners etc ..    

JEditorPane editorCopy = editorOryginal  // now i only copy reference to editorOryginal

//but i would like to get copy of object:

JEditorPane editorCopy = editorOryginal.getCopyInstance();       
editorOryginal.destroy(); // in JEditorPane this method not exists but we assume existing this method
editorCopy.something(); // here i have my copy but oryginal has been destroyed

1 个答案:

答案 0 :(得分:0)

Java中没有一般的机制。对于允许复制对象的类,它应该实现复制机制(例如Cloneable)。

原则上,我认为可以使用reflection复制对象,一次挑选一个成员并构建副本,但是很难使其工作。请注意,这意味着您还必须访问私有成员。即使你成功了,也不能保证它会像你期望的那样无法控制的课程......

考虑一下:

class A {
    int i;
}

class B {
    A a;
}

class C {
    B b;
}

void f(C c) {
    C c2 = c.getCopyInstance();

    // What is c2.b now?
}

c2.b应该与c.b相同(即c2是浅拷贝)还是应该是c.b(深拷贝)的新副本?在某些情况下,您需要深层复制,但对于共享资源(例如代表屏幕或磁盘的东西),您只想分配引用。一般来说,没有办法决定复制对象的正确方法。