我在理解类型推断中的捕获时遇到了问题。我有一些代码看起来像这样:
import java.util.EnumSet;
class A {
static enum E1 {
X
}
private static <T extends Enum<T>> EnumSet<T> barEnum(Class<T> x) {
return null;
}
private static void foo1(EnumSet<E1> s, E1 e) {
EnumSet<E1> x2 = barEnum(e.getClass());
}
private static void foo2(EnumSet<E1> s) {
EnumSet<E1> x = barEnum(s.iterator().next().getClass());
}
}
编译时会出现两个错误:
Test.java:15: error: method barEnum in class A cannot be applied to given types;
EnumSet<E1> x2 = barEnum(e.getClass());
^
required: Class<T>
found: Class<CAP#1>
reason: inference variable T has incompatible equality constraints E1,CAP#2
where T is a type-variable:
T extends Enum<T> declared in method <T>barEnum(Class<T>)
where CAP#1,CAP#2 are fresh type-variables:
CAP#1 extends E1 from capture of ? extends E1
CAP#2 extends E1 from capture of ? extends E1
Test.java:19: error: method barEnum in class A cannot be applied to given types;
EnumSet<E1> x = barEnum(s.iterator().next().getClass());
^
required: Class<T>
found: Class<CAP#1>
reason: inference variable T has incompatible equality constraints E1,CAP#2
where T is a type-variable:
T extends Enum<T> declared in method <T>barEnum(Class<T>)
where CAP#1,CAP#2 are fresh type-variables:
CAP#1 extends E1 from capture of ? extends E1
CAP#2 extends E1 from capture of ? extends E1
Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 errors
在尝试理解错误时,我将foo2
更改为捕获getClass()
的值,并将其存储在本地变量中,以查看实际类型:
private static void foo2(EnumSet<E1> s) {
// this works
Class<? extends Enum> c = s.iterator().next().getClass();
EnumSet<E1> y = barEnum(c);
}
现在,错误已经消失,代码已编译。我不明白引入一个与表达式完全相同的本地变量如何改变类型推断算法并解决问题。