所以,让我们有一个字符串列表和一个带有Hamcrest匹配器的函数,并返回matches()提供的匹配器的方法结果:
public boolean matchIt(final Matcher<? super List<String>> matcher) {
final List<String> lst = obtainListFromSomewhere();
return matcher.matches(lst);
}
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.现在我可以轻松打电话:
matchIt(empty());
matchIt(anything());
matchIt(hasItem("item"));
matchIt(everyItem(equalToIgnoringCase("item")));
Run Code Online (Sandbox Code Playgroud)
...因为所有这些工厂静态方法都生成一个适合方法签名的匹配器Matcher<? super List<String>>.
但是,我相信该matchIt()方法也应该接受一个接受Iterable对象的匹配器:
matchIt(everyItem(anything()));
Run Code Online (Sandbox Code Playgroud)
所以我天真地改变了matchIt()方法签名:
public boolean matchIt(final Matcher<? super List<? super String>> matcher);
Run Code Online (Sandbox Code Playgroud)
但它根本不起作用.它不仅不接受everyItem(anything()),甚至不接受以前正确的everyItem(equalToIgnoringCase("item"))说法(1.7.0_05编译器版本):
actual argument Matcher<Iterable<String>> cannot be converted to Matcher<? super List<? super String>> by method invocation conversion
Run Code Online (Sandbox Code Playgroud)
什么?那么这里有什么问题?它是matchIt()方法签名还是everyItem()错误设计的Hamcrest签名?或者只是Java泛型系统无法修复?非常感谢您的评论!
编辑@rlegendi我的目的是为客户端提供一个接口来添加和执行有关列表的谓词.那是matchIt()方法.matchIt(anything())在这种情况下,调用是有意义的,客户端想知道列表是否是任何内容.调用matchIt(empty())意味着客户端想要知道列表是否为空.反之为matchIt(everyItem(equalToIgnoringCase("item")))和 …