Java的:我怎样才能动态地创建基于对象的类型指定类型的数组? [英] Java: How can I dynamically create an array of a specified type based on the type of an object?
本文介绍了Java的:我怎样才能动态地创建基于对象的类型指定类型的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想借此传递一个名单,我知道是同质的,并从它创建同一类型为其中的元素的数组。
喜欢的东西...
列表<对象> LST =新的ArrayList<对象&gt ;;lst.add(新整型(3));/// 别的地方 ...断言(my_array的instanceof整数[]);
解决方案
转换会发生运行,而类型是在编译时丢失。所以,你应该做的是这样的:
公开< T> T []的toArray(列表< T>名单){
clazz类= list.get(0).getClass(); //检查大小和之前空
T []数组=(T [])java.lang.reflect.Array.newInstance(clazz中,则为list.size());
返回list.toArray(数组);
}
但要注意3号线之上可能会引发异常 - 它不是类型安全的。
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[]);
解决方案
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.
这篇关于Java的:我怎样才能动态地创建基于对象的类型指定类型的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文