java利用反射扩展任意数组的方法
package com.company; import java.lang.reflect.Array; import java.util.Arrays; /** * java利用反射扩展任意数组的方法 */ public class TestReflect { public static void main(String[] args) { int[] arr = {1,2,3,4,5}; int[] o = (int[]) exprendArrayLength(arr, 8); System.out.println(Arrays.toString(o)); } public static Object exprendArrayLength(Object a, int newLength){ Class<?> aClass = a.getClass(); if(!aClass.isArray()){ return null; } Class<?> componentType = aClass.getComponentType(); int length = Array.getLength(a); Object newArray = Array.newInstance(componentType, newLength); System.arraycopy(a,0,newArray,0,Math.min(length,newLength)); return newArray; } }
运行结果: