您的位置:首页 > 编程语言 > Java开发

【Java】 数组拷贝的通用方法

2015-02-12 15:21 369 查看
方法来源自《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;
}


Class<?> java.lang.Class.getComponentType(),获取元素类型。
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类提供的数组拷贝方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: