Java反射-NoSuchMethodException当方法存在时抛出 [英] Java Reflection - NoSuchMethodException Thrown when method exists
问题描述
我正在尝试创建一个采用两个字符串参数并在对象上调用方法调用的方法.这两个参数将提供className和methodName.理想情况下,我想使用反射来查找对象和方法,然后调用该方法.这是我管理的自动化套件.
I am trying to create a method which takes two string parameters and invokes a method call on an object. The two parameters would supply the className and methodName. Ideally I wanted to use reflection to find the object and method to then invoke the method. This is for an automation suite I manage.
public void executeMethod(String className, String methodName){
Class object = className.getClass();
Method objMethod = object.getMethod(methodName);
objMethod.invoke(pageObject);
}
运行它时,我收到错误NoSuchMethodException:java.lang.String.isPageDisplayed().
When I run it, I receive an error NoSuchMethodException: java.lang.String.isPageDisplayed() .
我认为我的问题在于寻找对象或与对象有关的事情.
I believe my issue exists with the finding the object or something to do with the object.
如果我执行上述相同的方法,如下所示,它将起作用:
If I execute the same method above as shown below, it works:
public void executeMethod(String className, String methodName){
Method objMethod = knownObject.class.getMethod(methodName);
m1.invoke(pageObject);
}
有人可以帮助我弄清楚我做错了吗?在这种情况下,我尝试调用的方法是public static void方法.
Could anyone help me figure out I am doing wrong? The method, in this case, I am trying to call is public static void method.
推荐答案
由于className
的类型为String
,因此className.getClass()
仅返回一个Class<String>
,显然它没有将该方法作为成员.相反,您应该使用
Since className
is of type String
, className.getClass()
just returns a Class<String>
which obviously does not have the method as a member. Instead, you should use Class.forName(className)
:
public void executeMethod(String className, String methodName){
Class<?> clazz = Class.forName(className);
Method objMethod = clazz.getMethod(methodName);
objMethod.invoke(pageObject);
}
这篇关于Java反射-NoSuchMethodException当方法存在时抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!