Java Reflection - NoSuchMethodException Thrown whe

2019-07-28 07:29发布

问题:

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