lundi 2 mars 2015

Java Reflection invoking method NoSuchMethodException

I'm trying to invoking a method from a class which the name of that class is given by the user. The program looks like this:



import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;

public class Test {

public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, InstantiationException {
Scanner in = new Scanner(System.in);
String className = in.nextLine();
Class c = Class.forName(className);
Object myObj = c.newInstance();
Method m = c.getDeclaredMethod("equals", new String("test").getClass());
Object retn = m.invoke(myObj, new String("testing").getClass());
}
}


I'm trying to execute this program by giving the input: java.lang.String


But I always get NoSuchMethodException:



Exception in thread "main" java.lang.NoSuchMethodException: java.lang.String.equals(java.lang.String)
at java.lang.Class.getDeclaredMethod(Class.java:2122)
at Test.main(Test.java:14)


And I know that the method equals is declared in the class java.lang.String. So what am I doing wrong?


I hid the try catch blocks because I didn't think it was necessary to express my doubt here. Hopefully someone can help me.






Aucun commentaire:

Enregistrer un commentaire