泛型行为在 JDK 8 和 9 中有所不同
以下简单类(用于重现它的存储库):
import static org.hamcrest.*;
import static org.junit.Assert.assertThat;
import java.util.*;
import org.junit.Test;
public class TestGenerics {
@Test
public void thisShouldCompile() {
List<String> myList = Arrays.asList("a", "b", "c");
assertThat("List doesn't contain unexpected elements", myList, not(anyOf(hasItem("d"), hasItem("e"), hasItem("f"))));
}
}
行为取决于 JDK 版本:
- 在 JDK 中正确编译<=8(使用 7 和 8 进行测试)
- 使用 JDK 9+ 编译失败(使用 9、10 和 11 EA 进行测试)
出现以下错误:
[ERROR] /tmp/jdk-issue-generics/src/test/java/org/alostale/issues/generics/TestGenerics.java:[17,17] no suitable method found for assertThat(java.lang.String,java.util.List<java.lang.String>,org.hamcrest.Matcher<java.lang.Iterable<? super java.lang.Object>>)
method org.junit.Assert.<T>assertThat(java.lang.String,T,org.hamcrest.Matcher<? super T>) is not applicable
(inference variable T has incompatible bounds
upper bounds: java.lang.String,java.lang.Object
lower bounds: capture#1 of ? super T?,capture#2 of ? super java.lang.Object,capture#3 of ? super java.lang.Object,java.lang.Object,java.lang.String,capture#4 of ? super T?)
method org.junit.Assert.<T>assertThat(T,org.hamcrest.Matcher<? super T>) is not applicable
(cannot infer type-variable(s) T
(actual and formal argument lists differ in length))
这是JDK 9中的一些预期更改还是一个错误?
我可以以这种方式将匹配器提取到类型化变量中,并且它将起作用:
Matcher<Iterable<? super String>> m1 = hasItem("d");
Matcher<Iterable<? super String>> m2 = hasItem("e");
Matcher<Iterable<? super String>> m3 = hasItem("f");
assertThat(myList, not(anyOf(m1, m2, m3)));
但问题仍然是:<=8能够推断类型,而不是9+,这是否正确?javac