1、 获得a数组对应的类对象
Class cl = a.getClass();
2、确认是一个数组
if (!cl.isArray()){
return null;
}
3、使用Class类的getComponentType方法确定数组对应的类型
Class componentType = cl.getComponentType();
4、构造新数组
Object newArray = Array.newInstance(componentType,length);
源代码:
public static Object goodCopyOf(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,length);
System.arraycopy(a,0,newArray,0,Math.min(length,newLength));
return newArray;
}