Skip to content

Improvement at interface in WebElement and SearchContext #3211

@leocarmona

Description

@leocarmona

I was wondering if is possible to change the return the generic type for this method below of the interfaces SearchContext and WebElement:

List< WebElement> findElements(By by)

to

List<? extends WebElement> findElements(By by);

import java.util.Arrays;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.WrapsDriver;
import org.openqa.selenium.internal.WrapsElement;

public class NewWebElement implements WebElement, WrapsDriver, WrapsElement {

	private WebElement wrappedElement;

	public NewWebElement(WebElement wrappedElement) {
		this.wrappedElement = wrappedElement;
	}
	
	public boolean isPresent() {
		try {
			this.getWrappedElement().isEnabled();
			
			return true;
		} catch (StaleElementReferenceException e) {
			return false;
		}
	}

	/**
	 * I want to created a class to extends the functionality of WebElement	
	 * Today because of the interface the code List<NewWebElement> will not compile although the NewWebElement implements WebElement.
	 * If the return chenged to List<? extends WebElement> will be possible create new custom functionalities. 
	 */
	@Override
	public List<NewWebElement> findElements(By by) {
		List<WebElement> webElements = this.getWrappedElement().findElements(by);
		NewWebElement[] newWebElements = new NewWebElement[webElements.size()];
		
		for (int i = 0; i < newWebElements.length; i++)
			newWebElements[i] = new NewWebElement(webElements.get(i));
		
		return Arrays.asList(newWebElements);
	}
	
	// Add unimplemented methods

}
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Sample {

	public static void main(String[] args) {
		WebDriver driver = new FirefoxDriver();
		driver.get("https://www.google.com");
		
		WebElement body = driver.findElement(By.tagName("body"));
		By search = By.id("lst-ib");
		
		// I will be able to find within an element and access my custom methods
		
		new newWebElement(body).findElements(search).get(0).isPresent();
	}
	
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions