public class 动态代理生成泛型数组 {
public static void main(String[] args) {
int[] a = {1, 2, 3};
a = (int[])goodCopyOf(a, 10);
System.out.println(Arrays.toString(a));
String[] b = {"TonT", "Dick", "Harry"};
b = (String[])goodCopyOf(b, 10);
System.out.println(Arrays.toString(b));
}
/**
参数用Object类型原因是int[]类型数组无法转换为Object[]类型的数组
*/
public static Object goodCopyOf(Object a, int newLength) {
Class cl = a.getClass();
if (!cl.isArray()) {
return null;
}
//返回类组件类型的数组
Class componentType = cl.getComponentType();
System.out.println(componentType.getName());
//查看该数组的长度
int length = Array.getLength(a);
//生成一个长度为newLength的类型为componentType的数组
Object newArray = Array.newInstance(componentType, newLength);
System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
return newArray;
}
}