2012-02-04 10 views
6

He estado buscando en el 'tanto' y 'y' métodos en el org.hamcrest.core.CombinableMatcher en hamcrest 1.2Hamcrest CombinableMatcher - Método Genérico no se compilará

Por alguna razón, no puedo 't obtener lo siguiente para compilar

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

el mensaje de compilación que se ve es

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>) 

Si especifico el parámetro de tipo explícitamente para el método, funciona

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

Aunque esto no es tan agradable.

¿Alguien puede decirme por qué el compilador no puede entender los tipos aquí? No puedo creer que este sea el comportamiento esperado en este caso.

Gracias!

Respuesta

5

El compilador debe inferir LHS <: String (§15.12.2.7 (A) continuación (B)) de la que por supuesto puede deducir trivialmente LHS = String. JDK 7 respeta la especificación (y puede especificar la fuente y el destino como 5 como en javac -source 5 -target).

+0

+1 Thanks much much :) –

2

Apagué un error de compilación similar (mientras usaba java 1.8 y hamcrest 1.3) porque mi primer matcher era nullValue() que devuelve el tipo 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>) 

Si usa nullValue(BigDecimal.class), compilará.

assertThat(BigDecimal.ONE, 
    is(both(not(nullValue(BigDecimal.class))) 
     .and(not(comparesEqualTo(BigDecimal.ZERO))))); 
Cuestiones relacionadas