我正在研究 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
这是我用来从主函数中读取类的函数,然后我想使用参数“test”和 null 来 getMethod(),其中“test”是方法的名称,null 表示该方法没有参数。我正在阅读的班级名为 myclass2,位于此处:
package a8;
public class myclass2 {
void test(){
//"takes no parameters"
//"returns bool"
//"name starts with test"
//return true;
}
}
正如您所看到的,该方法确实存在于类中。如果您能指出我的错误,我将不胜感激。
公开您的测试方法。我相信 Class.getMethod() 仅限于公共方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)