Java:如何根据对象的类型动态创建指定类型的数组?

我想采用一个我知道是同类的传递List,并从中创建一个与其中元素相同类型的数组。

就像是…

List lst = new ArrayList; lst.add(new Integer(3)); /// somewhere else ... assert(my_array instanceof Integer[]); 

转换将在运行时发生,而类型在编译时丢失。 所以你应该这样做:

 public  T[] toArray(List list) { Class clazz = list.get(0).getClass(); // check for size and null before T[] array = (T[]) java.lang.reflect.Array.newInstance(clazz, list.size()); return list.toArray(array); } 

但要注意上面的第3行可能会抛出exception – 它不是类型安全的。

此方法是类型安全的,并处理一些空值(至少一个元素必须为非null)。

 public static Object[] toArray(Collection c) { Iterator i = c.iterator(); for (int idx = 0; i.hasNext(); ++idx) { Object o = i.next(); if (o != null) { /* Create an array of the type of the first non-null element. */ Class type = o.getClass(); Object[] arr = (Object[]) Array.newInstance(type, c.size()); arr[idx++] = o; while (i.hasNext()) { /* Make sure collection is really homogenous with cast() */ arr[idx++] = type.cast(i.next()); } return arr; } } /* Collection is empty or holds only nulls. */ throw new IllegalArgumentException("Unspecified type."); } 
 java.lang.reflect.Array.newInstance(Class componentType, int length) 

如果你需要根据只在运行时知道的类型动态创建一个数组(假设你正在做reflection或generics),你可能需要Array.newInstance