Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics Copy Constructor

I'm wanting to code a copy constructor for a generically defined class. I have an inner class Node, which I am going to use as the nodes for a binary tree. When I pass in a 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 generically define a copy constructor.

like image 608
Morgan Kenyon Avatar asked Oct 07 '13 02:10

Morgan Kenyon


People also ask

What is the alternative for copy constructor in Java?

clone() acts like a copy constructor. Typically it calls the clone() method of its superclass to obtain the copy, etc. until it eventually reaches Object 's clone() method. The special clone() method in the base class Object provides a standard mechanism for duplicating objects.

Do generic classes need constructors?

A generic constructor is a constructor that has at least one parameter of a generic type. We'll see that generic constructors don't have to be in a generic class, and not all constructors in a generic class have to be generic.

Why copy constructor is not used in Java?

In Java it simply copies the reference. The object's state is not copied so implicitly calling the copy constructor makes no sense.

Is there any copy constructor in Java?

Like C++, Java also supports a copy constructor. But, unlike C++, Java doesn't create a default copy constructor if you don't write your own.


1 Answers

T can't guarantee that class it represents will have required constructor so you can't use new T(..) form.

I am not sure if that is what you need but if you are sure that class of object you want to copy will have copy constructor then you can use reflection 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());
}
like image 64
Pshemo Avatar answered Oct 13 '22 18:10

Pshemo