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

来源:互联网 发布:用淘宝卖东西 编辑:程序博客网 时间:2024/05/16 02:30

方法来源自《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类提供的数组拷贝方法。

0 0
原创粉丝点击