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

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

问题描述

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

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


< T> T [] toArray(T [] a)

返回包含此集合中所有元素的数组;返回的数组的运行时类型是指定数组的运行时类型。如果集合适合指定的数组,则返回其中。否则,将使用指定数组的运行时类型和此集合的大小分配新数组。

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屋!

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