如何在运行时实例化给定数组类型的 Java 数组?

如何在运行时实例化给定数组类型的 Java 数组?

How to instantiate a Java array given an array type at runtime?

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

< 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 类型的数组?


使用静态方法

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

可以在此处找到有关其使用的教程:
http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html


通过查看 ArrayList 是如何做到的:

1
2
3
4
5
6
7
8
public < T > T[] toArray(T[] a) {
    if (a.length < size)
        a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}

1
Array.newInstance(Class componentType, int length)


要创建一个泛型类型的新数组(仅在运行时知道),您必须创建一个对象数组,然后简单地将其转换为泛型类型,然后照样使用它。这是 Java 泛型实现的限制(擦除)。

1
T[] newArray = (T[]) new Object[X]; // where X is the number of elements you want.

然后该函数获取给定的数组 (a) 并使用它(事先检查它的大小)或创建一个新数组。


推荐阅读

    vim运行linux命令?

    vim运行linux命令?,系统,工作,信息,地址,命令,标准,时间,情况,工具,基础,linu

    linux下并行运行命令?

    linux下并行运行命令?,系统,服务,工作,命令,环境,网络,暂停,文件,脚本,参数,l

    linux下并行运行命令?

    linux下并行运行命令?,系统,服务,工作,命令,环境,网络,暂停,文件,脚本,参数,l

    linux命令行后台运行?

    linux命令行后台运行?,服务,状态,标准,暂停,命令,后台,连续,地方,工作,方法,l

    脚本运行linux命令?

    脚本运行linux命令?,系统,环境,工具,工作,位置,底部,代码,发行,官网,终端,lin

    linux进程运行命令?

    linux进程运行命令?,系统,工作,状态,地址,信息,进程,基础,命令,管理,软件,lin

    linux显示运行命令?

    linux显示运行命令?,系统,服务,状态,信息,工具,数据,电脑,标准,管理,时间,如

    linux运行vim命令?

    linux运行vim命令?,系统,工具,官方网站,模式,基础,数据,代码,环境,入口,命令

    linux监控命令运行?

    linux监控命令运行?,系统,工作,地址,信息,工具,情况,标准,环境,命令,状态,lin

    linux中命令停止运行?

    linux中命令停止运行?,系统,代码,第一,命令,进程,指令,程序,方法,接线,硬盘,l

    linux自动运行命令?

    linux自动运行命令?,服务,系统,时间,代码,周期性,第一,命令,管理,在线,状态,l

    linux开启运行命令?

    linux开启运行命令?,系统,服务,工作,管理,状态,命令,标准,情况,环境,工具,lin

    linux运行wps命令?

    linux运行wps命令?,软件,官网,名称,时间,电脑,系统,工具,环境,项目,数据,wps

    linux运行cmd命令?

    linux运行cmd命令?,电脑,系统,状态,情况,环境,命令,单位,管理,设备,数据,电脑

    linux运行两个命令?

    linux运行两个命令?,网络,地址,系统,工作,暂停,命令,网站,密码,网上,入口,Lin

    linux命令运行代码?

    linux命令运行代码?,代码,单位,系统,环境,连续,保险,工具,命令,文件,音乐,Lin

    linux命令运行脚本?

    linux命令运行脚本?,代码,系统,工作,设计,状态,命令,脚本,文件,目录,终端,运

    linux上运行的命令?

    linux上运行的命令?,系统,工作,软件,网络,地址,信息,情况,命令,灵活,基础知

    linux怎么运行命令?

    linux怎么运行命令?,系统,工作,首页,工具,终端,地址,命令,信息,电脑,情况,怎

    linux右击运行命令?

    linux右击运行命令?,系统,工作,设备,标准,首页,发行,电脑,终端,命令,文件,lin