使用反射编写泛型数组代码-扩展任意类型的数组

       Java.lang.reflect包中的Array类允许动态的创建数组。例如,将这个特性应用到Arrays类中的copyOf方法实现中,应该记得这个方法可以用于扩展已经填满的数组。

Employee[] a = new Employee[100];
...
//array is full
a = Arrays.copyOf(a, 2 * a.length);

       如何编写这样一个通用的方法呢?为此,需要java.lang.reflect包中Array类的一些方法。其中最关键的是Array类中的静态方法newInstance,它能够构造新数组。在调用它时必须提供两个参数,一个是数组的元素类型,一个是数组的长度。

       Object newArray = Array.newInstance(componentType, newLength);

       可以通过调用Array.getLength(a)获得数组的长度。而要获得新数组元素类型,就需要进行一下工作:

1) 首先获得a数组的类对象。

2) 确认它是一个数组。

3) 使用Class类的getComponentType方法确定数组对应的类型。

以下程序显示了扩展数组的方法。请注意,将badCopyOf的返回值进行类型转换将会

抛出一个异常。

package arrays;


import java.lang.reflect.Array;
import java.util.Arrays;

public class CopyOfTest {
    /**
     * This method attempts to grow an array by allocating a new array and copying all elements.
     */
    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.
     */
    public static Object goodCopyOf(Object a, int newLength) {
        Class cl = a.getClass();
        if(!cl.isArray())   return null;
        Class componentType = cl.getComponentType();
        int length = Array.getLength(a);
        Object newArray = Array.newInstance(componentType, newLength);
        System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
        return newArray;
    }

    /**
     * This program demonstrates the use of reflection for manipulating arrays.
     */
    public static void main(String[] args) {
        int a[] = { 1, 2, 3 };
        a = (int[])goodCopyOf(a, 10);
        System.out.println(Arrays.toString(a));

        /*
        System.out.println("The following call will generate an exception.");
        int b[] = { 1, 2, 3 };
        b = badCopyOf(b, 10);
        System.out.println(Arrays.toString(b));
        */
    }
}

编译并执行,程序运行结果如下:

arrays.CopyOfTest
[1, 2, 3, 0, 0, 0, 0, 0, 0, 0]

进程完成,退出码 0

猜你喜欢

转载自blog.csdn.net/m0_37732829/article/details/81869327