这就是我试图做的事情:
import java.lang.reflect.*;
class exampleOuter <T extends Number>
{
private exampleInner<T>[] elements;
public exampleOuter(Class<T> type, int size)
{
elements = (exampleInner<T>[]) Array.newInstance(type, size);
}
}
我被告知,如果我想创建类型为T的通用数组,我应该使用
elements = (T[]) Array.newInstance(type,size);
所以我尝试将其扩展到我的自定义类,并得到了ClassCastException(Ljava.lang.Double;无法转换为Lmypackagename.exampleInner;我在main中声明类如下:
exampleOuter<Double> test = new exampleOuter(Double.class,15);
我可以正常声明内部类,也可以声明非泛型的内部类数组,因此我想问题可能出在外部类的构造函数中。有什么想法?
EDIT: I understand what the problem is. When I create a new instance of the array, I create an array of doubles, not of exampleInner. I think. If that s right, I need to find a way to create an array of exampleInner while passing just Double.class to the function.
EDIT 2: I realize generic arrays are not typesafe, but I have to use them anyway because my teacher demands that we use them.
EDIT 3: I was told that to use generic arrays I had to allocate them that way, and to do so I need reflections, I think. The compiler tells me the class is using unsafe or unchecked operations, but I have to use generic arrays and that s the way I know to do it. If there s a better way I ll change the code.