java 使用 CoreMatchers.allOf() 的“Matcher <? extends String> [] 类型的可变参数参数的未检查泛型数组创建”警告

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17679405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 14:39:12  来源:igfitidea点击:

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

javagenericsgeneric-collectionshamcrest

提问by k1eran

In my UT code, extract below, I see warning :

在我的 UT 代码中,摘录如下,我看到警告:

Unchecked generic array creation for varargs parameter of
type Matcher <? extends String> []

Unchecked generic array creation for varargs parameter of
type Matcher <? extends String> []

I have read in another stackoverflow answerabout the problems using a generic parameter to a varargs method.

我在另一个stackoverflow 答案中阅读了关于使用可变参数方法的通用参数的问题。

But is there a neat way to slightly restructure this test to get rid of the ugly warning and avoid @SuppressWarnings?

但是有没有一种巧妙的方法来稍微重组这个测试以摆脱丑陋的警告并避免@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"))));
    }


}

回答by newacct

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

如果这是 Java 7+,那么您使用的库可以使用@SafeVarargs. 但是,这不在您的控制之下。

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-nullvalue of this type without an unchecked operation somewhere (either in your method or some other method that you call).

否则无法避免使用此方法出现未经检查的警告,因为该方法从根本上需要一个参数化类型的数组,并且不可能在null某处(在您的方法或您调用的其他一些方法)。

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

或者,查看 的文档CoreMatchers,似乎您可以考虑使用 的替代重载allOf,它采用Iterableof 匹配器代替。您无需未经检查的操作即可使用。