简体   繁体   English

是否可以在Java中复制对象而不修改类本身(例如添加复制构造函数)?

[英]Can I copy an object in Java without modifying the class itself (like adding a copy constructor)?

In my project I use an object from an external library, I need to make a copy of this object but I cannot modify the class in the library. 在我的项目中,我使用外部库中的对象,我需要制作该对象的副本,但无法修改库中的类。 How can I do that? 我怎样才能做到这一点?

This is the class of the object that I must copy: 这是我必须复制的对象的类:

public class Tree<T> implements Iterable<Tree<T>> {
    private List<Tree<T>> children;
    private T value;
    private Tree<T> tree = this;

     ... 
    }

您可以扩展该类,根据需要实现特定的对象,并可以在其中添加其他功能。

If the class doesn't implement Cloneable, there isn't a good way of doing this. 如果该类未实现Cloneable,则没有好的方法。

The acceptable way of doing it is just to write a utility method to copy the class manually, but that assumes you have some understanding of its internal structure. 可接受的方法是编写一个实用程序方法来手动复制该类,但这假定您对它的内部结构有所了解。

For example, you can do a shallow copy as follows: 例如,您可以按以下方式进行浅表复制:

T newTree = new T();
for (T t : tree) {
    newTree.add(t);
}

But since your class contains sub-trees, those won't be copied; 但是,由于您的课程包含子树,因此不会复制那些子树。 it would only be a shallow copy (the new tree would contain references to the subtrees in the old tree). 它只会是一个浅表副本(新树将包含对旧树中子树的引用)。

For a deep copy, you will have to recursively copy the subtrees as well. 对于深层复制,还必须递归复制子树。 I don't really understand enough about the structure of your class to write code for it. 我对您的类的结构了解不足,无法为其编写代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 How can I copy existing class object to other class new class object without creating copy of original object(in memory) in Java - How can I copy existing class object to other class new class object without creating copy of original object(in memory) in Java 如何使此副本构造函数在Java中进行深层复制? - How can I make this copy constructor make a deep copy in java? 在Java中复制对象而不影响原始的via拷贝构造函数 - Copying an Object in Java without affecting the original via copy constructor 如何在Java中复制对象? - How can I copy an object in Java? 如何在我的类中使用复制构造函数和静态字段? - How can I use copy constructor and static fields in my class? 完成Java中类的精确副本的构造函数 - Completing a constructor for an exact copy of a class in Java Java:具有可复制成员的Runnable成员的对象的深层复制 - Java: deep copy of object with Runnable member with copy constructor 如何使一个类将自身复制到可以使用Java执行的具有不同名称的另一个类中? - How to make a class copy itself into another class with a different name that can be executed with Java? 如何使用Java中的父抽象复制构造函数复制子类? - How can I copy subclasses by using the parent abstract copy constructor in Java? 复制构造函数类实例化 - Copy constructor Class instantiation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM