【问题标题】:How to copy unknown object?如何复制未知对象?
【发布时间】:2014-10-24 09:18:20
【问题描述】:

我想知道如何在 Java 中复制对象。但我的意思是复制而不实现可克隆接口,而是复制已经存在的对象,其中所有包含其他对象,例如:

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

【问题讨论】:

标签: java swing serialization io clone


【解决方案1】:

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 的新拷贝(深拷贝)?在某些情况下,您会想要一个深层副本,但对于共享资源(例如,代表屏幕或磁盘的东西),您只想分配引用。一般来说,没有办法决定什么是复制对象的正确方法。

【讨论】:

  • 请注意,现有的库已经处理了所有这些,例如 Apache BeanUtils。
  • 对于一般对象?例如,我会假设 BeanUtils 只处理 bean。无论如何,我认为没有任何方法可以按预期适用于所有类型的对象。
猜你喜欢
  • 1970-01-01
  • 2022-01-05
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
相关资源
最近更新 更多