Search code examples
javaselenium-webdriverwrapper

How to override findElements method so it returns list of type that implements WebElement interface


There is an interface WebElement.

I want to make a wrapper UIElement, that implements WebElement.

I've overridden all methods.

But faced one problem with findElementS method that returns List<WebElement>. I've tried to change return type to List<UIElement>, but code returns an error: "attempting to use incompatible return type". And it's weird for me, because it was not a problem to override findElement method and specify UIElement as return type.

Here is my method that IDE doesn't give to use with error from above:

List<UIElement> list = new ArrayList<>();
    for (WebElement el : this.element.findElements(by)) {
        UIElement uiElement = new UIElement(this.driver, el);
        list.add(uiElement);
    }
    return list;

Here is UIElement class and constructors:

public class UIElement implements WebElement {
private final WebDriver driver;
private final WebElement element;
private final Actions actions;
private final JavascriptExecutor jsExecutor;
private final Waiter waiter;


public UIElement(WebDriver driver, By by) {
    this.driver = driver;
    this.element = this.driver.findElement(by);
    this.actions = new Actions(this.driver);
    this.jsExecutor = (JavascriptExecutor) this.driver;
    this.waiter = new Waiter(this.driver);
}

public UIElement(WebDriver driver, WebElement element) {
    this.driver = driver;
    this.element = element;
    this.actions = new Actions(this.driver);
    this.jsExecutor = (JavascriptExecutor) this.driver;
    this.waiter = new Waiter(this.driver);
}
}

Solution

  • It is not possible to change the "List of Webelement" to "List of UIElement" in the overrided method.

    You cant change generic type of List to subtype of that generic type. Problem is that reference to any instance can be subtype of that instance

    Refer this link for more details- Stackoverflow