为了账号安全,请及时绑定邮箱和手机立即绑定

泛型行为在JDK 8和9中有所不同

泛型行为在JDK 8和9中有所不同

PIPIONE 2021-04-09 17:04:02
下面的简单类(通过repo重现它):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)));但是问题仍然是:javac<= 8是否能够推断类型,但是在9+中不是吗?
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 209 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信