【发布时间】:2015-06-02 14:55:23
【问题描述】:
我试图弄清楚为什么这段代码不能在 JDK 1.8.0_45 上编译:
public class Example<E extends Example<E>> {
public List<? extends Example<?>> toExamples(Collection<String> collection) {
return collection.stream()
.map(v -> lookup(v))
.collect(Collectors.toList());
}
public static <E extends Example<E>> E lookup(String value) {
return null;
}
}
添加一个看似不必要的演员表修复它:
public class Example<E extends Example<E>> {
public List<? extends Example<?>> toExamples(Collection<String> collection) {
return collection.stream()
.map(v -> (Example<?>) lookup(v))
.collect(Collectors.toList());
}
public static <E extends Example<E>> E lookup(String value) {
return null;
}
}
这是编译器的错误:
Example.java:9: error: incompatible types: inference variable R has incompatible bounds
.collect(Collectors.toList());
^
equality constraints: List<Object>
upper bounds: List<? extends Example<?>>,Object
where R,A,T are type-variables:
R extends Object declared in method <R,A>collect(Collector<? super T,A,R>)
A extends Object declared in method <R,A>collect(Collector<? super T,A,R>)
T extends Object declared in interface Stream
由于某种原因,lookup() 的返回类型未正确推断为扩展 Example 的内容。
【问题讨论】:
-
出于好奇,它是否可以在任何以前的 Java 8 版本上编译?这份报告似乎非常相关:bugs.openjdk.java.net/browse/JDK-8077304
-
您得到的确切错误信息是什么?
-
也可以更改lookup的签名:
public static <E extends Example<E>> Example<E> lookup(String value) -
又一个泛型方法的实例,声称返回调用者希望的任何东西......
标签: java java-8 type-inference java-stream