利用反射扩展数组长度

利用反射扩展数组长度

思想:要扩展数组长度其实就是产生一个新的数组覆盖旧的数组

import java.lang.reflect.*;

public class Answer {

    public static void main(String[] args) {

        Test test = new Test();

        test.print(); //打印数组的内容

        test.is = (int[]) addArrayLength(test.is, 10);  //用新的数组覆盖旧的数组
        test.ss = (String[]) addArrayLength(test.ss, 10);  

        test.print();

    }

    public static Object addArrayLength(Object array, int newLength) {
        Object newArray = null;
        Class componentType = array.getClass().getComponentType();  //得到一个数组的class对象
        newArray = Array.newInstance(componentType, newLength);     //动态创建数组
        System.arraycopy(array, 0, newArray, 0, Array.getLength(array));  //数组之间的复制
        return newArray;
    }
}

class Test {

    public int[] is = { 1, 2, 3 };

    public String[] ss = { "A", "B", "C" };

    public void print() {

        for (int index = 0; index < is.length; index++) {
            System.out.println("is[" + index + "]=" + is[index]);
        }

        System.out.println();

        for (int index = 0; index < ss.length; index++) {
            System.out.println("ss[" + index + "]=" + ss[index]);
        }

        System.out.println();

    }

}

备注:

array.getClass().getComponentType() 得到一个数组的class对象
Array.newInstance(componentType, newLength)  动态创建指定类型的数组
System.arraycopy(array, 0, newArray, 0, Array.getLength(array)) 实现数组之间的复制,这五个参数分别代表被复制的数组,起始位置,复制到的数组,起始位置,长度
务实,说实话!
原文地址:https://www.cnblogs.com/xtuxiongda/p/8586361.html