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 在我receieved类。我只需要将程序更改为:
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);
}
}
?如果我这样做,我会得到同样的例外。我在这种情况下做错了什么?
+0
'equals(String _)'没有在'String'和'Class '不是'String'对象。 –
2015-03-02 18:37:13