Java: call a method with name stored in variable

Om Prakash Sao :

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!

Greg Depoire-Ferrer :

The simplest way to do this is to use reflection:

String command = "click";
WebElement element = driver.findElement(By.id("id1"));

Method method = WebElement.class.getMethod(command);
method.invoke(element);

If you also want to call By.id with reflection, then you can do this:

String command = "click";
String id = "id";

Method byMethod = By.class.getMethod(id, String.class);
WebElement element = driver.findElement((By) byMethod.invoke(null, "id1"));

Method method = WebElement.class.getMethod(command);
method.invoke(element);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=430261&siteId=1