泛型很棘手。 而且在不同的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编译器的版本差异。
EnumSet.of(foo)
的类型为EnumSet<Enum>
,这与边界C extends Enum<C> & Another
不兼容。 - Daniel Pryden