如何在运行时实例化给定数组类型的Java数组? [英] How to instantiate a Java array given an array type at runtime?
问题描述
在Java集合框架中,Collection接口声明了以下方法:
In the Java collections framework, the Collection interface declares the following method:
返回包含此集合中所有元素的数组;返回的数组的运行时类型是指定数组的运行时类型。如果集合适合指定的数组,则返回其中。否则,将使用指定数组的运行时类型和此集合的大小分配新数组。
Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.
如果要实现这个方法,你将如何创建一个 a 类型的数组,仅在运行时才知道?
If you wanted to implement this method, how would you create an array of the type of a, known only at runtime?
推荐答案
p>使用静态方法
java.lang.reflect.Array.newInstance(Class<?> componentType, int length)
有关使用的教程可以在这里找到:
http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance .html
A tutorial on its use can be found here: http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html
这篇关于如何在运行时实例化给定数组类型的Java数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!