[英]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.