NoSuchMethodException Thrown when method exists

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);  
}

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);
}

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.


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);  
}

The String className should be Object class. Otherwise it assumes the method is inside an instance of String.


Assuming you have the object on which you want to invoke the method then pass it to the method instead of the class name. Also, you should use getDeclaredMethod , not getMethod :

public void executeMethod(Object object, String methodName) {
    Class clazz = object.getClass(); 
    Method method = clazz.getDeclaredMethod(methodName); 
    method.invoke(object);  
}
链接地址: http://www.djcxy.com/p/76512.html

上一篇: 需要关于OAuthException代码2500的帮助

下一篇: NoSuchMethodException方法存在时抛出