Java反射,getMethod()
我正在学习Java反射的基础知识,并观察有关类方法的信息。我需要得到一个与getMethod()函数描述的规范相匹配的方法。然而,当我这样做的时候,我得到了一个NoSuchMethodException,我希望您能告诉我为什么我的实现不正确Java反射,getMethod(),java,class,reflection,methods,Java,Class,Reflection,Methods,我正在学习Java反射的基础知识,并观察有关类方法的信息。我需要得到一个与getMethod()函数描述的规范相匹配的方法。然而,当我这样做的时候,我得到了一个NoSuchMethodException,我希望您能告诉我为什么我的实现不正确 static void methodInfo2(String className) throws ClassNotFoundException, NoSuchMethodException{ Class cls = null;
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获取method(),其中“test”是方法的名称,null表示方法没有参数。我正在阅读的课程名为myclass2,如下所示:
package a8;
public class myclass2 {
void test(){
//"takes no parameters"
//"returns bool"
//"name starts with test"
//return true;
}
}
如您所见,该方法实际上并不存在于类中。如果你能指出我的错误,我将不胜感激 公开你的测试方法。我相信Class.getMethod()仅限于公共方法。如果不发布确切的异常和输出,很难判断,但我怀疑这是因为类位于两个单独的包中,并且由于方法的默认修饰符受到保护,因此失败了
使用
getDeclaredMethod()
获得一个通常不可见的方法。是的,你比我先找到了+1来自JavaDoc forgetMethod()
:“返回一个方法对象,该方法对象反映由该类对象表示的类或接口的指定公共成员方法。”不,它们在同一个包中。不过,上面的答案是有效的。可能会默认为private。无论哪种方式,如果使用getDeclaredMethod()
都可以访问任何内容。