Java:类型安全:为 varargs 参数创建 A 的通用数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3981579/
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-10-30 04:15:10  来源:igfitidea点击:

Java: Type safety : A generic array of A is created for a varargs parameter

javacastingvariadic-functions

提问by Albert

Possible Duplicate:
Is it possible to solve the “A generic array of T is created for a varargs parameter” compiler warning?

可能的重复:
是否可以解决“为可变参数参数创建了 T 的通用数组”编译器警告?

Consider this is given:

考虑这是给定的:

interface A<T> { /*...*/ }
interface B<T> extends A<T> { /*...*/ }
class C { /*...*/ }
void foo(A<T>... a) { /*...*/ }

Now, some other code wants to use foo:

现在,其他一些代码想要使用foo

B<C> b1 /* = ... */;
B<C> b2 /* = ... */;
foo(b1, b2);

This gives me the warning

这给了我警告

Type safety : A generic array of A is created for a varargs parameter

So I changed the call to this:

所以我把电话改成了这样:

foo((A<C>) b1, (A<C>) b2);

This still gives me the same warning.

这仍然给我同样的警告。

Why? How can I fix that?

为什么?我该如何解决?

回答by ColinD

All you can really do is suppress that warning with @SuppressWarnings("unchecked"). Java 7 will eliminate that warning for client code, moving it to the declaration of foo(A... a)rather than the call site. See the Project Coin proposal here.

您真正能做的就是使用@SuppressWarnings("unchecked"). Java 7 将消除对客户端代码的警告,将其移至声明foo(A... a)而不是调用站点。在此处查看 Project Coin 提案。

回答by Bert F

Edit: Answer updated to reflect that question was updated to show A is indeed generic.

编辑:答案已更新以反映该问题已更新以显示 A 确实是通用的。

I would think that A must be a generic to get that error. Is A a generic in your project, but the code sample above leaves the generic decl out?

我认为 A 必须是泛型才能获得该错误。A 是您项目中的泛型,但上面的代码示例没有使用泛型 decl 吗?

If so,Because A is generic,you can't work around warning cleanly. Varargs are implemented using an array and an array doesn't support generic arrays as explained here:

如果是这样,因为 A 是通用的,所以你不能干净地解决警告。Varargs 是使用数组实现的,数组不支持通用数组,如下所述:

Java generics and varargs

Java 泛型和可变参数

回答by Eugene Kuleshov

You can try this:

你可以试试这个:

<T> void foo(T... a) { /*...*/ }