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])
See more on this question at Stackoverflow