方法来源自《Java核心教程》,有一定改动。
import java.lang.reflect.Array;
import java.util.Arrays;
public static Object MultiCopyOf(Object rhs, int newLength) {
Class<?> tmp=(Class<?>) rhs.getClass();
if(!tmp.isArray()) {
return null;
}
Object newArray=Array.newInstance(tmp.getComponentType(), newLength);
System.arraycopy(rhs, 0, newArray, 0, Math.min(Array.getLength(rhs), newLength));
return newArray;
}
Object java.lang.reflect.Array.newInstance(Class<?> componentType, int length) throws NegativeArraySizeException
函数原型,为反射数组对象创建新数组的静态方法。
void java.lang.System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
System类提供的数组拷贝方法。

本文介绍了一种基于Java反射机制的数组复制方法MultiCopyOf,该方法能够将一个已存在的数组复制到一个新长度的数组中,并展示了如何使用Class.getComponentType()、Array.newInstance()和System.arraycopy()等关键API。
1354

被折叠的 条评论
为什么被折叠?



