【发布时间】:2015-06-03 14:18:05
【问题描述】:
以下程序在 Java 7 和 Eclipse Mars RC2 for Java 8 中编译:
import java.util.List;
public class Test {
static final void a(Class<? extends List<?>> type) {
b(newList(type));
}
static final <T> List<T> b(List<T> list) {
return list;
}
static final <L extends List<?>> L newList(Class<L> type) {
try {
return type.newInstance();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
使用javac 1.8.0_45编译,报如下编译错误:
Test.java:6: error: method b in class Test cannot be applied to given types;
b(newList(type));
^
required: List<T>
found: CAP#1
reason: inference variable L has incompatible bounds
equality constraints: CAP#2
upper bounds: List<CAP#3>,List<?>
where T,L are type-variables:
T extends Object declared in method <T>b(List<T>)
L extends List<?> declared in method <L>newList(Class<L>)
where CAP#1,CAP#2,CAP#3 are fresh type-variables:
CAP#1 extends List<?> from capture of ? extends List<?>
CAP#2 extends List<?> from capture of ? extends List<?>
CAP#3 extends Object from capture of ?
一种解决方法是在本地分配一个变量:
import java.util.List;
public class Test {
static final void a(Class<? extends List<?>> type) {
// Workaround here
List<?> variable = newList(type);
b(variable);
}
static final <T> List<T> b(List<T> list) {
return list;
}
static final <L extends List<?>> L newList(Class<L> type) {
try {
return type.newInstance();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
我知道 Java 8 中的类型推断发生了很大变化 (e.g. due to JEP 101 "generalized target-type inference")。那么,这是一个错误还是一个新的语言“功能”?
编辑:我也已将此问题作为 JI-9021550 报告给 Oracle,但以防万一这是 Java 8 中的“功能”,我也已向 Eclipse 报告了该问题:
【问题讨论】:
-
嗨 Lukas,我们还不能称之为 eclipse 错误;请取消选择我的答案:(
-
@bayou.io:你是对的。完成!
标签: java compiler-errors java-8 type-inference