我有一个顶级Link class
,它在Selenium支持库中扩展SlowLoadableComponent
。
这个class
旨在直接实例化,并由class
扩展,为Link
提供更具体的行为,从而导致特定类型的资源。同时,我有一个generified lambda函数,它应该采用WebElement
,Link class
并提供指定Link class
的实例。我在设计基础结构时遇到一些困难,当我尝试创建lambda函数的实例以传递给构造函数时,我的类型参数不在其范围内,这种方式不会导致编译器抱怨我的类型参数不在其范围内另一堂课。
Link class
(缩减为最小代码):
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.LoadableComponent;
import org.openqa.selenium.support.ui.SlowLoadableComponent;
import org.openqa.selenium.support.ui.SystemClock;
public class Link<T extends LoadableComponent<T>> extends SlowLoadableComponent<T> {
private final WebElement link;
private final WebDriver driver;
public Link(final WebDriver driver, final WebElement link, final int timeoutInSeconds) {
super(new SystemClock(), timeoutInSeconds);
this.link = link;
this.driver = driver;
}
@Override
protected void load() {
PageFactory.initElements(driver, this);
}
@Override
protected void isLoaded() throws Error {
try {
assertTrue(link.isDisplayed());
} catch (NoSuchElementException e) {
throw new Error(e);
}
}
}
lambda函数:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.lang.reflect.Constructor;
import java.util.function.Function;
public class GetLinkFunction<L extends Link> implements Function<WebElement,L> {
private final WebDriver driver;
private final Class<? extends L> linkClass;
public GetLinkFunction(WebDriver driver, Class<? extends L> linkClass) {
this.driver = driver;
this.linkClass = linkClass;
}
public final L apply(WebElement element)
{
try {
Constructor<? extends L> linkConstructor = linkClass.getConstructor(WebDriver.class, WebElement.class);
return (linkClass.cast(linkConstructor.newInstance(driver, element)));
} catch(Exception e) {
System.out.print("Failed to construct an instance of link class " + linkClass.toString());
return null;
}
}
}
现在,调用Lambda函数的构造函数:
//This line causes the error-- the compiler complains that the type parameter Link is not within its bounds and should extend Link. I was under the impression that a type parameter like 'L extends Link' should accept Link and any sub-class of Link.
GetLinkFunction function = new GetLinkFunction<Link>(driver, Link.class));
所以,我有一个想法,因为Link是参数化的,这就是我的问题所在。我该如何解决这个问题?我不知道要为Link本身声明什么类型参数,但这也会导致问题:
GetLinkFunction function = new GetLinkFunction<Link<Link>>(driver, Link.class));
答案 0 :(得分:0)
您正在使用原始类型的Link
作为通用界限。
变化:
public class GetLinkFunction<L extends Link> implements Function<WebElement,L> {
对此(假设您需要链接类型也是链接):
public class GetLinkFunction<L extends Link<? extends Link & LoadableComponent>> implements Function<WebElement, L> {