此代码会导致用javac编译错误(但是,值得注意的是,不使用Eclipse 4.2.2!):为什么在这里不允许转换为“GenericType <?>”?
public interface Foo<T> {
}
class Bar<T> implements Foo<Iterable<T>> {
}
class Test {
void test(Foo<? extends Iterable<? extends String>> foo) {
Bar<?> bar = (Bar<?>) foo;
}
}
从javac的错误是这样的:
Foo.java:9: error: inconvertible types
Bar<?> bar = (Bar<?>) foo;
^
required: Bar<?>
found: Foo<CAP#1>
where CAP#1 is a fresh type-variable:
CAP#1 extends Iterable<? extends String> from capture of ? extends Iterable<? extends String>
更改强制转换为(Bar) foo
(即使用原始类型)允许编译代码,也可以将foo
的类型更改为Foo<? extends Iterable<?>>
。
编辑:欢快的,这个简单的变化使得Eclipse的拒绝,但javac的接受:
void test(Foo<Iterable<String>> foo) {
Bar<?> bar = (Bar<?>) foo;
}
而且,Eclipse和javac的拒绝此一:
void test(Foo<Iterable<? extends String>> foo) {
Bar<?> bar = (Bar<?>) foo;
}
希望你永远不必像这样做任何丑陋的铸造,这只是一个好奇的问题... – jahroy
是的只是好奇心。真实生活中的例子实际上是“instanceof Bar”工作但“instanceof Bar >”没有的检查实例。 –
这里有一些提及,http://docs.oracle.com/javase/tutorial/java/generics/capture.html –