首页 > 代码库 > 通过反射修改已有数组的大小

通过反射修改已有数组的大小

import java.lang.reflect.Array;

public class ChangeArrayDemo {
    public static void main(String[] args) {
        int temp[] = { 1, 2, 3 };
        int newTemp[] = (int[]) arrayInc(temp, 5);
        print(newTemp);
        System.out.println("\n=============================");
        String t[] = { "von", "mldn", "java" };
        String nt[] = (String[]) arrayInc(t, 8);
        print(nt);
    }

    public static Object arrayInc(Object obj, int len) {
        Class<?> c = obj.getClass();
        Class<?> arr = c.getComponentType();
        Object newO = Array.newInstance(arr, len);
        int co = Array.getLength(obj);
        System.arraycopy(obj, 0, newO, 0, co);
        return newO;
    }

    public static void print(Object obj) {
        Class<?> c = obj.getClass();
        if (!c.isArray()) {
            return;
        }
        Class<?> arr = c.getComponentType();
        System.out.println(arr.getName() + "Array‘s length is:"
                + Array.getLength(obj));
        for (int i = 0; i < Array.getLength(obj); i++) {
            System.out.print(Array.get(obj, i) + ",");
        }
    }
}

通过反射修改已有数组的大小