Java Reflection - NoSuchMethodException Thrown when method exists

懵懂的女人 提交于 2019-12-11 05:18:42

问题


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.


回答1:


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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/42099669/java-reflection-nosuchmethodexception-thrown-when-method-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!