List casting interface is failing in Java
本问题已经有最佳答案,请猛点这里访问。
我有以下接口:
1 2 | public interface CustomWebElement extends WebElement . . . methods |
在以下情况下,当我试图将
1 | CustomWebElement a = (CustomWebElement) element.findElement(by); //findElement return WebElement |
但是对返回
1 | List<CustomWebElement> a = (List<CustomWebElement>) element.findElements(by); |
例外情况:
1 | Inconvertable types; Cannot cast List<WebElement> to List<CustomWebElement> |
在这种情况下,
请查看http://docs.oracle.com/javase/tutorial/java/generics/
在使用泛型时使用通配符可能会有所帮助喜欢
List extends WebElement>
这是因为
Arrays differ from generic types in two important ways. First, arrays are covariant.
This scary-sounding word means simply that if Sub is a subtype of Super, then the
array type Sub[] is a subtype of Super[]. Generics, by contrast, are invariant: for
any two distinct types Type1 and Type2, List is neither a subtype nor a
supertype of List