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

 

一个对象数组不能转换成雇员数组(Employee[ ])。如果这样做,则在运行时 Java 将会产生 ClassCastException 异常。前面已经看到,Java 数组会记住每个元素的类型,即创建数组时 new 表达式中使用的元素类型。将一个 Employee[ ]临时地转换成 Object[ ] 数组, 然后再把它转换回来是可以的,但一 从开始就是 Objectt ] 的数组却永远不能转换成 Employe[]数组。为了编写这类通用的数组代码, 需要能够创建与原数组类型相同的新数组。为此, 需要 java.lang.reflect 包中 Array 类的一些方法。其中最关键的是 Array类中的静态方法 newlnstance,它能够构造新数组。在调用它时必须提供两个参数,一个是数组的元素类型,一个是数组的长度。

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

为了能够实际地运行,需要获得新数组的长度和元素类型。

可以通过调用 Array.getLength(a) 获得数组的长度,也可以通过 Array 类的静态 getLength方法的返回值得到任意数组的长度。而要获得新数组元素类型,就需要进行以下工作:

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

2 ) 确认它是一个数组。

3 ) 使用 Class 类(只能定义表示数组的类对象)的 getComponentType 方法确定数组对应的类型。

下面是一些常用的方法:

static Object get(Object array,int index)

static xxx get/xx(Object array,int index)

( xxx 是 boolean、byte、 char、 double、 float、 int、 long、 short 之中的一种基本类M。)

这些方法将返回存储在给定位置上的给定数组的内容。

static void set(Object array,int index,Object newValue)

static setXxx(Object array,int index,xxx newValue)

( xxx 是 boolean、 byte、char、double、float、 int、 long、 short 之中的一种基本类型。)

这些方法将一个新值存储到给定位置上的给定数组中。

static int getLength(Object array) 返回数组的长度。

static Object newInstance(Class componentType,int length)

static Object newInstance(Class componentType,int[]lengths)

返回一个具有给定类型、 给定维数的新数组。
package demo01;

import java.lang.reflect.*;
import java.util.*;


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);
   }

   
   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;
   }

   
   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;
   }
}
[1, 2, 3, 0, 0, 0, 0, 0, 0, 0]
[Tom, Dick, Harry, null, null, null, null, null, null, null]
The following call will generate an exception.
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
	at demo01.CopyOfTest.main(CopyOfTest.java:20)

猜你喜欢

转载自blog.csdn.net/qq_36186690/article/details/81186725