加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 编写复制数组的通用方法

发布时间:2020-12-15 04:30:50 所属栏目:Java 来源:网络整理
导读:对于我的编程任务,我被要求编写一个通用的复制方法,从一个数组复制到相同大小和类型的数组.这在 Java中甚至可能吗?我尝试的一切都以一些“通用数组创建”错误结束.我迷路了,不知道怎么解决这个问题! public class copyArrayAnyType{ public copyArray(AnyT
对于我的编程任务,我被要求编写一个通用的复制方法,从一个数组复制到相同大小和类型的数组.这在 Java中甚至可能吗?我尝试的一切都以一些“通用数组创建”错误结束.我迷路了,不知道怎么解决这个问题!

public class copyArray<AnyType>{

   public copyArray(AnyType[] original){ 

     AnyType[] newarray = new AnyType[original.length];  

     for(int i =0; i<original.length; i++){ 
        newarray[i] = original[i]; } 
}

解决方法

您可以使用反射的概念来编写可以在运行时确定类型的通用复制方法.简而言之,反射是在运行时检查类,接口,字段和方法的能力,而无需在编译时知道类,方法等的名称.

java.lang.Reflect与java.lang.Class一起构成Java Reflection API.此方法使用这两个类及其一些方法来创建一个通用的arrayCopy方法,该方法将为我们找出类型.

更多信息:What is reflection and why is it useful?

可能不熟悉的语法

>类<?>使用通配符运算符?这基本上说我们可以拥有一个未知类型的Class对象 – 类Class的通用版本.
>< T>是一个通用的运算符,代表raw type
> ArrayThe Array类提供动态创建和访问Java数组的静态方法.即,此类包含的方法允许您设置和查询数组元素的值,确定数组的长度,以及创建新的数组实例.我们将使用Array.newInstance()

反射API的方法

> getClass() – 返回一个包含Class对象的数组,这些对象表示作为所表示的类对象成员的所有公共类和接口.
> getComponentType() – 返回表示数组的组件类型(类型,即int等)的类.
> newInstance() – 获取数组的新实例.

private <T> T[] arrayCopy(T[] original) {

    //get the class type of the original array we passed in and determine the type,store in arrayType
    Class<?> arrayType = original.getClass().getComponentType();

    //declare array,cast to (T[]) that was determined using reflection,use java.lang.reflect to create a new instance of an Array(of arrayType variable,and the same length as the original
    T[] copy = (T[])java.lang.reflect.Array.newInstance(arrayType,original.length);

    //Use System and arraycopy to copy the array
    System.arraycopy(original,copy,original.length);
    return copy;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读