通过java的反射编写泛型数组

322.png


第一种方法:会抛出一个ClassCastException异常,因为这段代码返回的是对象数组(Object[])类型,不能转换成对应的数组类型。因此不提倡使用这种方法


public static Object[] badCopyOf(Object[] a, int newLength) {

  // 创建一个新的对象数组

  Object[] newArray = new Object[newLength];

  // 拷贝数组

  System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));

  return newArray;


 }



第二种方法:不需要声明为对象型数组,整型数组 int[]可以被转换成Object ,但是不能转换成对象型数组


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;

 }


猜你喜欢

转载自blog.51cto.com/14028890/2415053