lodgvideon / hamcrest

Automatically exported from code.google.com/p/hamcrest
0 stars 0 forks source link

Unavoidable unchecked generics array creation for a varargs parameter #190

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
The use of varargs parameters in the factories for aggregate matchers lead to a 
compiler warning when using non reifiable types.  For example:

        import static java.util.Arrays.asList;
        import static org.hamcrest.Matchers.contains;

        ...

        contains(asList(new Object()), asList(new Object()));

In some cases, I think the methods can be annotated with @SafeVarargs, 
Matchers.contains being a good example, because the equals matcher will 
correctly fail to match rather than throw an exception if the varargs arguments 
have inconsistent types.  As it stands, a method like this is needed to 
side-step the warning:

    @SafeVarargs
    public static <T> Matcher<Iterable<? extends T>> contains(final T... contents) {
        return Matchers.contains(new ArrayList<Matcher<? super T>>() {{
            for (T content : contents) {
                add(Matchers.equalTo(content));
            }
        }});
    }

Alternatively, if the contains methods and friends were overloaded with an 
implementation that took an Iterable<E> rather than an E... (which might 
require changing the signature of the varargs version to E, E...), the problem 
could be pushed out of the library's domain. 

Original issue reported on code.google.com by ms5...@gmail.com on 22 Dec 2012 at 4:24

GoogleCodeExporter commented 9 years ago
Thanks for raising this.

The @SafeVarargs annotation was introduced in Java 7, so we'll have to check 
that using it doesn't affect Hamcrest's compatibility with Java 5/6, but 
otherwise I see no reason not to proceed.

Original comment by t.denley on 30 Dec 2012 at 9:05

GoogleCodeExporter commented 9 years ago
Any news on this one?

Original comment by elvst...@gmail.com on 17 Jul 2013 at 10:56

GoogleCodeExporter commented 9 years ago
I hope this is on prioritized list since it is a bit annoying "feature". 
Maybe start new version (2.0) that will be depending on JDK7 so you can add 
this annotation?

Original comment by milanale...@gmail.com on 16 Jan 2015 at 2:40