我正在学习Java反射的基础知识,并观察有关类方法的信息。我需要获得一个与getMethod()函数所描述的规范相匹配的方法。然而,当我这样做时,我得到了一个NoSuchMethodException,我希望您能告诉我为什么我的实现是不正确的。
static void methodInfo2(String className) throws ClassNotFoundException,
NoSuchMethodException{
Class cls = null;
try{
cls = Class.forName(className);
} catch(ClassNotFoundException e){
e.printStackTrace();
}
System.out.println("Cls: "+cls);
Method method1 = cls.getMethod("test", null);
System.out.println("method1: "+method1);
}EDIT1:当我打印"Cls:"+cls时,输出是"Cls: class a8.myclass2“。为什么它要附加类部分?( a8是正确的,所以不用担心) /EDIT1
这是我用来从main函数中读入类的函数,然后我想使用参数“getMethod”和null来测试(),其中"test“是方法的名称,而null表示方法没有参数。我正在阅读的类名为myclass2,如下所示:
package a8;
public class myclass2 {
void test(){
//"takes no parameters"
//"returns bool"
//"name starts with test"
//return true;
}
}正如您所看到的,该方法实际上存在于类中。如果你能指出我的错误,我将不胜感激。
发布于 2011-12-03 01:58:57
公开你的测试方法。我相信Class.getMethod()仅限于公共方法。
发布于 2011-12-03 02:01:05
如果不发布确切的异常和输出,就很难判断,但我怀疑这是因为类在两个单独的包中,并且由于方法的默认修饰符只是protected,所以它失败了。
使用getDeclaredMethod()获取通常不可见的方法。
https://stackoverflow.com/questions/8360510
复制相似问题