关于java:java-反射的应用-扩充数组

public class ArrayLenExtend {
    public static Object goodCopy(Object oldArray, int newLength) {
//Array类型
         Class c = oldArray.getClass();
         System.out.println(c.getName());
//元素类型
         Class componentType = c.getComponentType();
         System.out.println(componentType.getName());
//创立新数组
         Object newArray = Array.newInstance(componentType, newLength);
//拷贝
        int oldLength = Array.getLength(oldArray);
        System.arraycopy(oldArray, 0, newArray, 0, oldLength);
//返回
        return newArray;
}
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5};
         a = (int[]) goodCopy(a,10);
         System.out.println(a.length);
    }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理