Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: call a method with name stored in variable

Tags:

java

selenium

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!

like image 511
Om Sao Avatar asked Aug 30 '17 11:08

Om Sao


People also ask

How do you call a method using variables?

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.

How can we use variable as a method name in Java?

String MyVar=2; MethodMyVar();

Can a method and variable have the same name Java?

Yes it's fine, mainly because, syntactically , they're used differently.

Can a method name be same as variable?

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.


1 Answers

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)

like image 58
JB Nizet Avatar answered Sep 23 '22 09:09

JB Nizet