Java Reflection调用方法NoSuchMethodException

时间:2015-03-02 18:33:20

标签: java reflection

我正在尝试从类中调用一个方法,该类的名称由用户提供。 该计划如下:

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());
}
}

我正在尝试通过输入来执行此程序: java.lang.String中

但我总是得到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)

我知道方法equals是在类java.lang.String中声明的。那么我做错了什么?

我隐藏了try catch块,因为我认为没有必要在这里表达我的怀疑。 希望有人可以帮助我。

编辑:

现在说我想执行该方法:     getDeclaredConstructors 在课上我收到了。我只需将程序更改为:

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);
}
}

?如果我这样做,我得到相同的例外。在这种情况下我做错了什么?

1 个答案:

答案 0 :(得分:5)

您正在尝试调用equals(String)类中的String方法,该方法不存在。要调用的方法是equals(Object)

Object.class作为参数类型传递给getDeclaredMethod

Method m = c.getDeclaredMethod("equals", Object.class);
相关问题