I have a requirement such that:
String command = "click"; // this can have value such as clear, getLocation, getSize, getTagName etc.
WebDriver driver = new ChromeDriver(options); //creating a webdriver object
driver.findElement(By.id("id1")).click(); //Here I want "click" method should be called dynamically as per what I have stored in variable `command`.
So, is there something possible like:
driver.findElement(By.id("id1")).<something to call click()>
I have already looked at Reflection in Java, but that looked to me complex as per my requirement. Any pointers will be helpful!
To call a method in Java from another class is very simple. We can call a method from another class by just creating an object of that class inside another class. After creating an object, call methods using the object reference variable.
String MyVar=2; MethodMyVar();
Yes it's fine, mainly because, syntactically , they're used differently.
As a method is called the values of its parameters are copied. In practice, this means that both the main method and the method to be called can use variables with the same name.
Your variable represents something you want to do with a web element (in this case, click on it).
The appropriate type for that is not String
. Use a Consumer<WebElement>
instead (or whatever the type of what driver.findElement()
returns is):
Consumer<WebElement> command = e -> e.click();
// ...
command.accept(driver.findElement(By.id("id1")));
This is type-safe, efficient, refactorable, and much more flexible than reflection (since your consumer can do whatever it wants with the element, not limited to a single method call without any argument. Like for example, enter some text in a text field)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With