reflection newinstance constructor java wrong number of arguments -
i learning reflection in java, , trying make example of constructor. there problem: "wrong number of arguments". searching through google , stackoverflow, cannot find same problem facing. can please me understand problem, thank much. codes:
public static void main(string[] args) { printclass f = new printclass(); class cl = f.getclass(); constructor<?> constructor[] = cl.getdeclaredconstructors(); // cl.getdeclaredconstructors() won't work... f.field1 = 3; printclass p1 = null; printclass p2 = null; try { p1 = (printclass) constructor[0].newinstance(); // constructor[0].newinstance((object[])args) won't work... p2 = (printclass) constructor[1].newinstance("this not printclass-------"); p1.print(); p2.print(); } catch (instantiationexception | illegalaccessexception | illegalargumentexception | invocationtargetexception e) { // todo auto-generated catch block e.printstacktrace(); } } } class printclass { string s = "this printclass..."; int field1; public printclass(string s) { this.s = s; } public printclass() { } public void print() { system.out.println(s); }
}
and error
java.lang.illegalargumentexception: wrong number of arguments @ sun.reflect.nativeconstructoraccessorimpl.newinstance0(native method) @ sun.reflect.nativeconstructoraccessorimpl.newinstance(unknown source) @ sun.reflect.delegatingconstructoraccessorimpl.newinstance(unknown source) @ java.lang.reflect.constructor.newinstance(unknown source) @ reflection.mainclass.main(mainclass.java:18)
again, thank helping me understand problem. :)
you're calling first of 2 constructors without argument. how can sure first constructor in array 1 without argument, , not 1 expecting string?
you can't, because the javadoc says:
the elements in array returned not sorted , not in particular order.
if want reference no-argument constructor of class, should call
cl.getdeclaredconstructor();
if want reference constructor taking string argument, should call
cl.getdeclaredconstructor(string.class);
Comments
Post a Comment