Aces 'n Eights
Aces 'n Eights

Reputation: 17

Calling a method with a variable name - possible?

I have a function for a Selenium Test that looks like this.

public static WebElement getElmObject (String locinfo, String loctype) {
    try{
      return driver.findElement(By.loctype(locinfo));
    } catch (Throwable t){
        return null;
}

The function is supposed to take in the info string and the type (the name of the method to call in the BY class - like xpath, cssselector, tagname etc.) How do I get Java to evaluate the value of "loctype"?

I come from a ColdFusion background and this is easy to do with CF but I am having a hard time trying to do this in Java. I just get a "cannot resolve method" issue and it won't compile. Is it even possible to do?

Upvotes: 0

Views: 263

Answers (2)

Devi Kiran
Devi Kiran

Reputation: 598

we can also do it with enum like this other than creating seperate methods for each and every locator like getElmObjectById as LaurentG said we can also achieve it as shown below

public enum avilableLocators
{
    CLASS_NAME, CSS_SELECTOR, XPATH
}

and have a method with switch case or if-else if which will have a return type of By

public By locinfo(String locinfo) 
{
 String locatorValue=null;
switch (locType(locinfo)) 
{
case XPATH:
           locatorValue=locinfo.split(",")[1]/*assuming that you are passing locinfo,locvalue*/ 
            return By.xpath(locator);
}
}

public final avilableLocators locType(String loctype) {

if (loctype.contains("xpath")) 
{

return avilableLocators.XPATH;
}

}



so  the final usage can be like this
String locDetails="xpath,//*[@id='ComScorePingFile']"
locinfo(locDetails);

Upvotes: 0

LaurentG
LaurentG

Reputation: 11757

You can do this using Reflection.

public static WebElement getElmObject(String locinfo, String loctype) {
    try {
        Method method = By.class.getMethod(loctype, String.class);
        By by = (By) method.invoke(By.class, locinfo);
        return driver.findElement(by);
    } catch (Throwable t) {
        return null;
    }
}

However I find this strange and I would recommend using different methods (getElmObjectById, getElmObjectByCss, etc.) or to use an enum (ID, CSS, XPATH, etc.) as parameter instead of the method name. Using the method name as parameter, it makes your caller dependent of the Selenium implementation. If they change the name of a method, your code will not work anymore and you will even not notice this at compile time!

Upvotes: 3

Related Questions