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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3152290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:35:59  来源:igfitidea点击:

Java: How can I dynamically create an array of a specified type based on the type of an object?

javaarrays

提问by JeffV

I would like to take a passed List that I know is homogeneous and from it create an array of the same type as the elements within it.

我想获取一个我知道是同构的传递列表,并从中创建一个与其中的元素类型相同的数组。

Something like...

就像是...

List<Object> lst = new ArrayList<Object>;

lst.add(new Integer(3));

/// somewhere else ...

assert(my_array instanceof Integer[]);

回答by Bozho

The conversion would happen runtime, while the type is lost at compile time. So you should do something like:

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

public <T> T[] toArray(List<T> 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);
}

But beware that the 3rd line above may throw an exception - it's not typesafe.

但请注意,上面的第三行可能会引发异常 - 它不是类型安全的。

回答by erickson

This method is type safe, and handles some nulls (at least one element must be non-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.");
}

回答by irreputable

java.lang.reflect.Array.newInstance(Class<?> componentType, int length)

回答by Steven Schlansker

If you need to dynamically create an array based on a type known only at runtime (say you're doing reflection or generics) you'll probably want Array.newInstance

如果您需要根据仅在运行时已知的类型动态创建数组(例如您正在执行反射或泛型),您可能需要Array.newInstance