java 学习笔记--利用反射实现泛型数组的复制

来源:互联网 发布:网络教育毕业总结 编辑:程序博客网 时间:2024/06/08 15:10

引用自Java核心技术卷I

使用反射编写泛型数组代码:

public class CopyOfTest {    public static void main(String[] args)    {        int[] a = { 1, 2, 3 };        a = (int[]) goodCopyOf(a, 10);        System.out.println(Arrays.toString(a));        String[] b = { "Tom", "Dick", "Harry" };        b = (String[]) goodCopyOf(b, 10);        System.out.println(Arrays.toString(b));        System.out.println("The following call will generate an exception.");        b = (String[]) badCopyOf(b, 10);    }    /**     * This method attempts to grow an array by allocating a new array and copying all elements.     * @param a the array to grow     * @param newLength the new length     * @return a larger array that contains all elements of a. However, the returned array has     * type Object[], not the same type as a     */    public static Object[] badCopyOf(Object[] a, int newLength) // not useful    {        Object[] newArray = new Object[newLength];        System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));        return newArray;    }    /**     * This method grows an array by allocating a new array of the same type and     * copying all elements.     * @param a the array to grow. This can be an object array or a primitive     * type array     * @return a larger array that contains all elements of a.     */    public static Object goodCopyOf(Object a, int newLength)    {        //获得字节码文件        Class cl = a.getClass();        //如果不是数据,应该返回        if (!cl.isArray()) return null;        //获得字节码的数据类型,比如int,boolean(这种方法不会返回int[])        Class componentType = cl.getComponentType();//获得组成类型        //String name = cl.getTypeName();//获得字节码类型-->比如int[],int之类的        //获得a数组的长度-->只有Array类型才可以使用        int length = Array.getLength(a);        //创建一个新的componentType类型数组对象        Object newArray = Array.newInstance(componentType, newLength);        //复制元素        System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));        return newArray;    }}

PS:之所以public static Object goodCopyOf(Object a, int newLength)方法中的第一个参数为Object而不是Object[]原因是:
1.如果定义为Object[],那么只能接受引用数据类型的数组(对象数组),对于int[]等基本数据类型的对象就符合要求了
2.定义为Object,整形数组int[]等基本类型数组可以转为Object(记住,万物皆对象)

        //创建一个String[]类型的数组        String[] strings = new String[100];        //创建一个Object类型的list        ArrayList<Object> list = new ArrayList<>();        //集合存进String[]数组,其实就是存了一个地址而已        list.add(strings);
阅读全文
0 0
原创粉丝点击