I am learning Reflection in Java, and trying to make an example of Constructor. But there is a problem: "wrong number of arguments". Searching through google and stackoverflow, I cannot find the same problem as I am currently facing. can anyone please help me to understand the problem, thank you so much. This is my codes:
public static void main(String[] args) {
PrintClass f = new PrintClass();
Class cl = f.getClass();
Constructor<?> constructor[] = cl.getDeclaredConstructors(); // cl.getDeclaredConstructors() also won't work...
f.field1 = 3;
PrintClass p1 = null;
PrintClass p2 = null;
try {
p1 = (PrintClass) constructor[0].newInstance(); // constructor[0].newInstance((Object[])args) also won't work...
p2 = (PrintClass) constructor[1].newInstance("this is not PrintClass-------");
p1.print();
p2.print();
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class PrintClass {
String s = "this is PrintClass...";
int field1;
public PrintClass(String s) {
this.s = s;
}
public PrintClass() {
}
public void print() {
System.out.println(s);
}
}
and this is the error
java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at reflection.MainClass.main(MainClass.java:18)
Again, thank you so much for helping me understand the problem. :)
Aucun commentaire:
Enregistrer un commentaire