反射泛型数组
public void reflectArrayCreatedTest() {
try {
String[] a1 = {"a", "b"};
String[] r1 = (String[]) badCopy(a1, 2);
System.out.println(Arrays.toString(r1));
} catch (ClassCastException e) {
e.printStackTrace();
}
System.out.println("=======");
String[] a2 = {"a", "b"};
String[] r2 = (String[]) goodCopy(a2, 2);
System.out.println(Arrays.toString(r2));
int[] a3 = {1, 2};
int[] r3 = (int[]) goodCopy(a3, 2);
System.out.println(Arrays.toString(r3));
}
public static Object[] badCopy(Object[] a, int newLength) {
Object[] newArray = new Object[newLength];
System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));
return newArray;
}
public static Object goodCopy(Object a, int newLength) {
Class<?> cl = a.getClass();
if (!cl.isArray()) return null;
Class<?> componentType = cl.getComponentType();
int length = Array.getLength(a);
Object newArray = Array.newInstance(componentType, newLength);
System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
return newArray;
}