luispcosta
luispcosta

Reputation: 572

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.

EDIT:

Say now that i wanted to execute the method: getDeclaredConstructors On the class i receieved. I would only have to change the program to:

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

public class Teste {

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.getMethod("getDeclaredConstructor");
    Object retn = m.invoke(myObj);
    System.out.println(retn);
}
}

? If i do this i get the same exception. What am i doing wrong in this case?

Upvotes: 1

Views: 4776

Answers (1)

rgettman
rgettman

Reputation: 178253

You are attempting to invoke the equals(String) method in the String class, which does not exist. The method to invoke is equals(Object).

Pass Object.class as the parameter type to getDeclaredMethod.

Method m = c.getDeclaredMethod("equals", Object.class);

Upvotes: 5

Related Questions