Java generics copy constructor

I want to write a copy constructor for a commonly defined class I have an inner class node, which I use as a node of a binary tree When I pass in a new object

public class treeDB <T extends Object> {
    //methods and such

    public T patient; 
    patient = new T(patient2);       //this line throwing an error
    //where patient2 is of type <T>
}

I just don't know how to define a copy constructor in general

Solution

T cannot guarantee that the class it represents will have a required constructor, so you cannot use the new t (..) Form

I'm not sure if this is what you need, but if you're sure that the object class you want to copy will have a copy constructor, you can use something like

public class Test<T> {

    public T createCopy(T item) throws Exception {// here should be
        // thrown more detailed exceptions but I decided to reduce them for
        // readability

        Class<?> clazz = item.getClass();
        Constructor<?> copyConstructor = clazz.getConstructor(clazz);

        @SuppressWarnings("unchecked")
        T copy = (T) copyConstructor.newInstance(item);

        return copy;
    }
}
//demo for MyClass that will have copy constructor: 
//         public MyClass(MyClass original)
public static void main(String[] args) throws Exception {
    MyClass mc = new MyClass("someString",42);

    Test<MyClass> test = new Test<>();
    MyClass copy = test.createCopy(mc);

    System.out.println(copy.getSomeString());
    System.out.println(copy.getSomeNumber());
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>