如何给出实例在运行时数组类型的Java数组? [英] How to instantiate a Java array given an array type at runtime?

查看:96
本文介绍了如何给出实例在运行时数组类型的Java数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java集合框架,Collection接口声明了以下方法:

In the Java collections framework, the Collection interface declares the following method:

<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/Collection.html#toArray(T%5b%5d)\"><$c$c><T> T []的toArray(T []一)

返回包含此collection中所有元素的数组;返回数组的运行时类型是指定数组的。如果集合指定数组能容纳,它返回此处。否则,一个新的数组分配一个具有指定数组的运行时类型和此collection的大小。

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.

如果你想实现这个方法,你会如何创建的类型的数组 ,只有在运行时知道的?

If you wanted to implement this method, how would you create an array of the type of a, known only at runtime?

推荐答案

使用静态方法

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

在其使用的教程可以在这里找到:
<一href=\"http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html\">http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html

这篇关于如何给出实例在运行时数组类型的Java数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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