利用反射标记创建泛型数组,是一种不错的方法
public class ArrayOfGeneric<T>
{
T[] array;
public ArrayOfGeneric4(Class<T> type, int size) {
/* to solution array of generic key code! */
array = (T[]) Array.newInstance(type, size);
}
public T get(int index) {
return array[index];
}
public T[] rep() {
return array;
}
public void set(int index, T t) {
array[index] = t;
}
public static void main(String[] args) {
ArrayOfGeneric<Integer> aog = new ArrayOfGeneric<Integer>(Integer.class, 10);
Object[] objs = aog.rep();
for (int i = 0; i < 10; i++) {
aog.set(i, i);
System.out.println(aog.get(i));
}
try {
Integer[] strs = aog.rep(); //用反射的方法好处就在这里,可以用实际类型接收
System.out.println(strs.length);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
} |