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.
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
, notgetMethod
:Since
className
is of typeString
,className.getClass()
just returns aClass<String>
which obviously does not have the method as a member. Instead, you should useClass.forName(className)
:The String className should be Object class. Otherwise it assumes the method is inside an instance of String.