I'm having this code. Why doesn't it works?(Working meaning that it display 3) How can I fix it?
public class Main {
public static<V> V copy(V var){
try{
return (V) var.getClass().getConstructor(var.getClass()).newInstance(var);
}
catch(Exception e){
System.out.println("Copy faield " + e.getMessage() + " ");
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
Integer a = new Integer(3);
Integer b = copy(a);
System.out.println(a);
System.out.println(b);
}
}
This is the output:
Copy faield java.lang.Integer.<init>(java.lang.Integer)
java.lang.NoSuchMethodException: java.lang.Integer.<init>(java.lang.Integer)
at java.lang.Class.getConstructor0(Class.java:2818)
at java.lang.Class.getConstructor(Class.java:1723)
at Main.copy(Main.java:7)
at Main.main(Main.java:19)
3
null
Thanks!
intorStringargument constructors, noIntegercopy constructor. With reflection, you cannot unbox the parameters automatically.