Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is giving me no such method exception?

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?

like image 329
user3239652 Avatar asked Oct 14 '25 08:10

user3239652


2 Answers

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])
like image 134
Jon Skeet Avatar answered Oct 16 '25 22:10

Jon Skeet


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)

like image 24
fge Avatar answered Oct 16 '25 22:10

fge