-2

Need to convert variable contains String to a method call.

Example:

Variable:

//Enter the name and value of the locator
public String[] LoginID_Button = {"name","Log in"};

In my another class:

 driver.findElement(By.name(loc1.LoginID_Button[1])).isDisplayed();

But I need to write as:

driver.findElement(By.loc1.LoginID_Button[0](loc1.LoginID_Button[1])).isDisplayed();

The name is the variable string but should be changed as Method. How to do this?

1 Answers1

0

This is called Reflection. Which, is the ability to change structure/behavior in runtime.

This is a nice question about it.

For your problem, you can do the same as in that question's accepted answer.

driver.findElement(By.class.getMethod(loc1.LoginID_Button[0],String.class).invoke(null,loc1.LoginID_Button[1])).isDisplayed();

In the above code, the method getMethod() is used to dynamically find a method by its name which in this case LoginId_Butt[0]. It is required also to specify the type of the parameters that target method is accepting, in our case, it is String.

The found method is then invoked using the invoke() method. The invoke() method takes two arguments, the first one is the instance that the dynamic method is executed against. In our case, the instance is null because the dynamic method is static. The second argument is a params of the arguments passed to the dynamic method. In this case, we have only one parameter to pass, that is LoginId_Butt[1].

Notes

  1. Please don't forget to wrap this code with ty/catch against many exceptions can be thrown.

  2. Please use the java naming convention for variable names i.e. loginID_Button

Amr Eladawy
  • 4,193
  • 7
  • 34
  • 52