Hamcrest CombinableMatcher - Generic Method无法编译

时间:2012-02-04 04:02:30

标签: java generics

我刚刚查看了hamcrest 1.2中org.hamcrest.core.CombinableMatcher上的'both'和'and'方法

出于某种原因,我无法得到以下内容来编译

@Test
public void testBoth() {
    String HELLO = "hello";
    String THERE = "there";
    assertThat("hello there", both(containsString(HELLO)).and(containsString(THERE)));
}

我得到的编译信息是

and(org.hamcrest.Matcher<? super java.lang.Object>) in org.hamcrest.core.CombinableMatcher<java.lang.Object> cannot be applied to (org.hamcrest.Matcher<java.lang.String>)

如果我为方法指定了类型参数explicity,它可以正常工作

@Test
public void testBoth() {
    String HELLO = "hello";
    String THERE = "there";
    Assert.assertThat("hello there", CombinableMatcher.<String>
        both(containsString(HELLO)).and(containsString(THERE)));
}

虽然这不是很好。

谁能告诉我为什么编译器无法弄清楚这里的类型?在这种情况下,我无法相信这是预期的行为。

谢谢!

2 个答案:

答案 0 :(得分:5)

编译器应该推断LHS <: String(§15.12.2.7(A)然后(B)),当然它可以简单地推导LHS = String。 JDK 7遵循规范(您可以将源和目标指定为javac -source 5 -target中的5)。

答案 1 :(得分:2)

我遇到了类似的编译错误(使用java 1.8和hamcrest 1.3时),因为我的第一个匹配器是Dealer account Vehicle Listings ,返回类型nullValue()

Object

如果使用assertThat(BigDecimal.ONE, is(both(not(nullValue())) .and(not(comparesEqualTo(BigDecimal.ZERO))))); ^---The method and(Matcher<? super Object>) in the type CombinableMatcher.CombinableBothMatcher<Object> is not applicable for the arguments (Matcher<BigDecimal>) ,则会编译。

nullValue(BigDecimal.class)