Java:如何根据对象的类型动态创建指定类型的数组? [英] Java: How can I dynamically create an array of a specified type based on the type of an object?

查看:25
本文介绍了Java:如何根据对象的类型动态创建指定类型的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

类似……

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

lst.add(new Integer(3));

/// somewhere else ...

assert(my_array instanceof Integer[]);

推荐答案

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

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

但要注意上面的第 3 行可能会抛出异常 - 它不是类型安全的.

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

这篇关于Java:如何根据对象的类型动态创建指定类型的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆