使用静态导入时如何提示类型推断?

Gab*_*bák 5 java generics type-inference hamcrest

我在单元测试中使用junit和hamcrest,我遇到了一个泛型问题:


assertThat(collection, empty());
Run Code Online (Sandbox Code Playgroud)

我知道类型推断不可用这种方式,其中一个解决方案是提供类型提示,但是在使用静态导入时应该如何键入提示?

irr*_*ble 3

虽然类型推断并不像我们希望的那么强大,但在这种情况下,实际上是 API 出了问题。它无缘无故地限制自己。is-empty 匹配器适用于任何集合,而不仅仅是特定的集合E

假设API是这样设计的

public class IsEmptyCollection implements Matcher<Collection<?>>
{
    public static Matcher<Collection<?>> empty()
    {
        return new IsEmptyCollection();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后assertThat(list, empty())按预期工作。

你可以尝试说服作者更改API。同时你可以有一个包装纸

@SuppressWarnings("unchecked")
public static Matcher<Collection<?>> my_empty()
{
    return (Matcher<Collection<?>>)IsEmptyCollection.empty();
}
Run Code Online (Sandbox Code Playgroud)