由于Java泛型的实现,你不能有这样的代码:
public class GenSet<E> {
private E a[];
public GenSet() {
a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation
}
}
如何在保持类型安全的同时实现这一点?
我在Java论坛上看到一个解决方案是这样的:
import java.lang.reflect.Array;
class Stack<T> {
public Stack(Class<T> clazz, int capacity) {
array = (T[])Array.newInstance(clazz, capacity);
}
private final T[] array;
}
但我真的不明白这是怎么回事。
我制作这个代码片段是为了反射地实例化一个简单的自动化测试实用程序所通过的类。
Object attributeValue = null;
try {
if(clazz.isArray()){
Class<?> arrayType = clazz.getComponentType();
attributeValue = Array.newInstance(arrayType, 0);
}
else if(!clazz.isInterface()){
attributeValue = BeanUtils.instantiateClass(clazz);
}
} catch (Exception e) {
logger.debug("Cannot instanciate \"{}\"", new Object[]{clazz});
}
注意这段:
if(clazz.isArray()){
Class<?> arrayType = clazz.getComponentType();
attributeValue = Array.newInstance(arrayType, 0);
}
用于数组初始化。newInstance(数组的类,数组的大小)。类可以是原语(int.class)和对象(Integer.class)。
BeanUtils是Spring的一部分。
你可以这样做:
E[] arr = (E[])new Object[INITIAL_ARRAY_LENGTH];
这是在Effective Java中实现泛型集合的建议方法之一;26项。没有类型错误,不需要重复强制转换数组。然而,这会触发警告,因为它有潜在的危险,应该谨慎使用。正如注释中所详细描述的,这个对象[]现在伪装成我们的E[]类型,如果不安全使用,可能会导致意外错误或classcastexception。
根据经验,只要强制转换数组在内部使用(例如支持数据结构),并且不返回或暴露给客户端代码,这种行为是安全的。如果需要向其他代码返回泛型类型的数组,则您提到的反射array类是正确的方法。
值得一提的是,在任何可能的情况下,如果您使用泛型,那么使用列表将比使用数组更愉快。当然,有时您别无选择,但使用集合框架要健壮得多。
您不需要将Class参数传递给构造函数。
试试这个。
public class GenSet<T> {
private final T[] array;
@SafeVarargs
public GenSet(int capacity, T... dummy) {
if (dummy.length > 0)
throw new IllegalArgumentException(
"Do not provide values for dummy argument.");
this.array = Arrays.copyOf(dummy, capacity);
}
@Override
public String toString() {
return "GenSet of " + array.getClass().getComponentType().getName()
+ "[" + array.length + "]";
}
}
and
GenSet<Integer> intSet = new GenSet<>(3);
System.out.println(intSet);
System.out.println(new GenSet<String>(2));
结果:
GenSet of java.lang.Integer[3]
GenSet of java.lang.String[2]