是否可以解决“为可变参数参数创建了 T 的通用数组"?编译器警告? [英] Is it possible to solve the "A generic array of T is created for a varargs parameter" compiler warning?
问题描述
这是有问题的代码的简化版本,一个泛型类使用另一个具有泛型类型参数的类,并且需要将其中一种泛型类型传递给具有可变参数的方法:
This is a simplified version of the code in question, one generic class uses another class with generic type parameters and needs to pass one of the generic types to a method with varargs parameters:
class Assembler<X, Y> {
void assemble(X container, Y... args) { ... }
}
class Component<T> {
void useAssembler(T something) {
Assembler<String, T> assembler = new Assembler<String, T>();
//generates warning:
// Type safety : A generic array of T is
// created for a varargs parameter
assembler.assemble("hello", something);
}
}
是否有任何正确的方法可以将泛型参数传递给可变参数方法而不会遇到此警告?
Is there any correct way to pass along the generic parameter to a varargs method without encountering this warning?
当然像
assembler.assemble("hello", new T[] { something });
不起作用,因为您无法创建通用数组.
does not work since you cannot create generic arrays.
推荐答案
在 Java 6 中,除了添加 @SuppressWarnings("unchecked")
,我不这么认为.
In Java 6, other than adding @SuppressWarnings("unchecked")
, I don't think so.
这个错误报告有更多信息,但归结为编译器不喜欢泛型数组.
This bug report has more information but it boils down to the compiler not liking arrays of generic types.
这篇关于是否可以解决“为可变参数参数创建了 T 的通用数组"?编译器警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!