ClockTok
ClockTok

Reputation: 31

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;

     ... 
    }

Upvotes: 0

Views: 294

Answers (2)

rghome
rghome

Reputation: 8841

If the class doesn't implement Cloneable, there isn't a good way of doing this.

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.

Upvotes: 1

NiVeR
NiVeR

Reputation: 9806

You can extend the class, implementing your specific object for your need, to which you can add the additional functionality.

Upvotes: 2

Related Questions