【发布时间】:2014-12-03 19:56:28
【问题描述】:
泛型很棘手。 并且看起来它们在不同版本的 Java 中的处理方式不同。
此代码在 Java 7 中成功编译,在 Java 8 中编译失败。
import java.util.EnumSet;
public class Main {
public static void main(String[] args) {
Enum foo = null;
tryCompile(EnumSet.of(foo));
}
static <C extends Enum<C> & Another> void tryCompile(Iterable<C> i) {}
static interface Another {}
}
这是来自 Java 8 的错误消息。我用这个来编译它:http://www.compilejava.net/
/tmp/java_A7GNRg/Main.java:6: error: method tryCompile in class Main cannot be applied to given types;
tryCompile(EnumSet.of(foo));
^
required: Iterable<C>
found: EnumSet
reason: inferred type does not conform to upper bound(s)
inferred: Enum
upper bound(s): Enum<Enum>,Another
where C is a type-variable:
C extends Enum<C>,Another declared in method <C>tryCompile(Iterable<C>)
/tmp/java_A7GNRg/Main.java:6: warning: [unchecked] unchecked method invocation: method of in class EnumSet is applied to given types
tryCompile(EnumSet.of(foo));
^
required: E
found: Enum
where E is a type-variable:
E extends Enum<E> declared in method <E>of(E)
1 error
1 warning
问题是关于Java编译器版本之间的差异。
【问题讨论】:
-
Java 8 抱怨什么?
-
确实,Java 8 中的编译错误应该解释为什么它无法编译。它很可能会......
-
你希望这段代码做什么?此外,您的
Enum是原始类型。 -
如果没有错误消息,很难猜出这里发生了什么,但我猜编译器能够(正确)推断
EnumSet.of(foo)的类型为EnumSet<Enum>不兼容绑定C extends Enum<C> & Another. -
完成,错误输出已添加到问题中。但它有什么帮助?
标签: java generics compiler-errors java-7 java-8