Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while type casting Webelement to Select

  1. In my web page there are multiple dropdowns with same property valuesto

  2. I am getting all those Webelements in a List

  3. Now fetching one WebElement from the List using index

  4. While trying to type cast this WebElement to Select I am getting error:

"java.lang.ClassCastException: org.openqa.selenium.remote.RemoteWebElement cannot be cast to org.openqa.selenium.support.ui.Select"

Please Help! Below is my code.

int index;
String sIndex = null;
By element = ORUtils.ORGenerator(pageName,objectName);
//Getting all the webelements with same name in myElement List
java.util.List<WebElement> myElements=WebUtils.driver.findElements(element);

//Get index of element on page
Pattern pIndex=Pattern.compile("(.*)");
Matcher mIndex=pIndex.matcher(objectName);
if(mIndex.find())
{
    sIndex=objectName.replaceAll("[a-z]","");
    sIndex=sIndex.replaceAll("[A-Z]","");
}

index=Integer.valueOf(sIndex);
index=index-1;
//Getting element from the List using index
WebElement myElement=myElements.get(index);

//Type casting WebElement to Select this is where i get the error**
Select myDropDown=(Select) myElement;

List<WebElement> listOfOptions = myDropDown.getOptions();
//List<WebElement> listOfOptions=myElement.
for(WebElement item : listOfOptions)
{
    if(Value.equals((item.getText())))
    {
        item.click();
        Thread.sleep(2000);
        break;
    }
}
like image 274
Surabhi Avatar asked Mar 17 '23 02:03

Surabhi


1 Answers

In java object typecasting one object reference can be type cast into another object reference. The cast can be to its own class type or to one of its subclass or superclass types or interfaces. So what you are doing is incorrect. To create object of Select using myElement do:

Select myDropDown=new Select(myElement);

To know more you can also try out by looking instanceOf. Here you can check it as:

if (myElement instanceof Select)
    System.out.println(true);
else
    System.out.println(false);

and you will get your answer.

like image 58
Vivek Singh Avatar answered Mar 28 '23 19:03

Vivek Singh