使用反射拷贝数组

    public static void main(String[] args) {
        int[] arr = {1,2,3};
        int[] obj = (int[])goodCopyOf(arr, 1);
        System.out.println(Arrays.toString(obj));

    }
    //使用反射创建泛型数组拷贝方法
    //Array.newInstance(getClass(), length)
    public static Object goodCopyOf(Object obj,int newLength){
        Class componentType = obj.getClass().getComponentType();
        Object newArray = Array.newInstance(componentType, newLength);
        int length = Array.getLength(obj);
        //拷贝数量
        System.arraycopy(obj, 0, newArray, 0, Math.min(length, newLength));
        return newArray;
    }
posted @ 2023-03-11 17:39  橘茶_OrangeTea  阅读(21)  评论(0)    收藏  举报