"Unchecked generic array creation for varargs parameter of type Matcher <? extends String> []" warning using CoreMatchers.allOf()

generic-collections, generics, hamcrest, java

Solution

If this is Java 7+, then the library you're using can annotate the method with `@SafeVarargs`. However, this is not under your control.

Otherwise there is no way to avoid an unchecked warning with this method, because the method fundamentally requires an array of a parameterized type, and it is impossible to obtain a non-`null` value of this type without an unchecked operation somewhere (either in your method or some other method that you call).

Or, looking at the documentation for `CoreMatchers`, it seems that you could consider using the alternate overload of the `allOf`, which takes an `Iterable` of matchers instead. That you can use without unchecked operations.

Problem

In my UT code, extract below, I see warning : `Unchecked generic array creation for varargs parameter of type Matcher <? extends String> []` I have read in another stackoverflow answer about the problems using a generic parameter to a varargs method. But is there a neat way to slightly restructure this test to get rid of the ugly warning and avoid `@SuppressWarnings`? ``` package stackoverflow; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test; import static org.junit.matchers.JUnitMatchers.containsString; import static org.hamcrest.CoreMatchers.not; public class FooTest { @SuppressWarnings({"unchecked"}) @Test public void sampleTest() { Assert.assertThat("foo bar", CoreMatchers.allOf( containsString("foo"), containsString("bar"), not(containsString("baz")))); } } ```

Original source

Related problems