I have this code:
Class I want to copy:
public class NormalChair extends AbstractChair {
protected int height;
protected String name;
public NormalChair() {
super();
}
public NormalChair(String name, int height) {
super(name, height);
}
// Copy constructor - getName() and getHeight() are defined in parent class.
public NormalChair(NormalChair chair) {
this(chair.getName(), chair.getHeight());
}
}
Create some class
public Object createObj(String cls_name, String param1, int param2){ return Class.forName(cls_name).getConstructor(String.class, Integer.class).newInstance(param1, param2); }
Then I try to copy object of that class using this:
Object obj_to_copy = createObj("Classname", "name", 10);
String cls_name = obj_to_copy.getClass().getName();
Class.forName(cls_name).getConstructor(Object.class).newInstance(obj_to_copy);
And I get this error:
Exception in thread "main" java.lang.NoSuchMethodException: test.NormalChair.<init>(java.lang.Object)
at java.lang.Class.getConstructor0(Class.java:2800)
at java.lang.Class.getConstructor(Class.java:1708)
at test.ProductTrader.create(ProductTrader.java:57)
at test.Test.main(Test.java:23)
So I suppose I need to call copy constructor somehow differently than showing it's type as Object?
P.S. Also I gave this example as simplistic. But in reality I would not know which class needs to be copied before runtime, so using copy constructor should not depend only on NormalChair class.
Update:
I updated my question, to make it more clear that when I copy object, before, runtime, I won't know what class it will need to copy.
Class.forName(cls_name).getConstructor(NormalChair.class)? - Andrew Logvinovobjc_to_copy.getClass()insidegetConstructor. - Andriusncthennc.getClass()will give theNormalChairclass - Sageheightandnamefields, but NormalChair is declaring duplicate fields (protected int height; protected String name;) with the same names. Although they have the same names they are not otherwise related, and they could have different values, leading to confusion and bugs. You should remove theheightandnamefields on class NormalChair. - Boann