How to hint type inference when using static imports?
I am using junit with hamcrest in my unit tests and I came acro开发者_如何学Css a generics problem:
assertThat(collection, empty());
I am aware of type inference not being available this way and that one of the solutions is to give a type hint, but how should I type hint when using static imports?
While type inference is not as powerful as we would like, in this case, it's really the API that's at fault. It unnecessarily restricts itself for no good reason. The is-empty matcher works on any collection, not just on collections of a specific E
.
Suppose the API is designed this way
public class IsEmptyCollection implements Matcher<Collection<?>>
{
public static Matcher<Collection<?>> empty()
{
return new IsEmptyCollection();
}
}
then assertThat(list, empty())
works as expected.
You can try to convince the author to change the API. Meanwhile you can have a wrapper
@SuppressWarnings("unchecked")
public static Matcher<Collection<?>> my_empty()
{
return (Matcher<Collection<?>>)IsEmptyCollection.empty();
}
I don't quite understand the problem. Here's the method I use:
/**
* A matcher that returns true if the supplied {@link Iterable} is empty.
*/
public static Matcher<Iterable<?>> isEmpty() {
return new TypeSafeMatcher<Iterable<?>>() {
@Override
public void describeTo(final Description description) {
description.appendText("empty");
}
@Override
public boolean matchesSafely(final Iterable<?> item) {
return item != null && !item.iterator().hasNext();
}
};
}
And I use it like this:
List<String> list = new ArrayList<String>();
assertThat(list, isEmpty());
No problem with generics here.
精彩评论