import java.lang.reflect.Constructor;
class tr1 {
public static void main(String[] args) {
try {
if (args.length < 1)
throw(new Exception("baby its wrong"));
Class s = Class.forName(args[0]);
Constructor c = s.getDeclaredConstructor(int.class, char.class, String.class, String.class);
Object o = c.newInstance(Integer.parseInt(args[1]), args[2].charAt(0), args[3], args[4]);
System.out.println("description of object " + o);
} catch (Exception e) {
System.out.println(e);
}
}
}
class A {
public A(int a, char c, String... strings){
System.out.println(a);
System.out.println(c);
for (String q:strings) {
System.out.println(q);
}
}
}
Why this code is giving me NoSuchMethod
exception? Any solution for it?
why this code is giving me nosuchmethod exception?
Because you don't have a constructor with the parameters you've requested:
(int, char, String, String)
You only have a constructor with these parameters:
(int, char, String[])
where the String[]
is a varargs parameter.
The fact that there's a varargs parameter is basically a compile-time artifact. You can detect this at execution time using Constructor.isVarArgs()
but that doesn't change the signature of the constructor.
any solution for it?
Use the existing constructor instead :)
Constructor c = s.getDeclaredConstructor(int.class, char.class, String[].class);
Object o = c.newInstance(Integer.parseInt(args[1]),
args[2].charAt(0),
new String[] { args[3], args[4] });
That creation of a String[]
to pass to the constructor is basically what the compiler would do for you if you called
new A(Integer.parseInt(args[1]), args[2].charAt(0), args[3], args[4])
Because an ellipsis is syntactic sugar for an array.
You should:
s.getDeclaredConstructor(int.class, char.class, String[].class);
(and as @JonSkeet mentions in his answer, you should also make your third argument an array in the .newInstance()
invocation)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With