栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

编写通用方法以复制数组

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

编写通用方法以复制数组

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

java.lang.reflect中连同java.lang.Class中包括Java反射API。此方法同时使用这些类和它们的某些方法来构成一个通用

arrayCopy
方法,该通用方法将为我们找出类型。

更多信息:反射是什么,为什么有用?

可能不熟悉的语法

  • Class<?>
    正在使用通配符运算符
    ?
    ,该运算符基本上表示我们可以有一个
    Class
    未知类型的对象-类的通用版本
    Class
  • <T>
    是代表原始类型的泛型运算符
  • Array
    Array类提供静态方法来动态创建和访问Java数组。即,此类包含的方法使您可以设置和查询数组元素的值,确定数组的长度以及创建数组的新实例。我们将使用
    Array.newInstance()

反射API中的方法

  • getClass ()
    -返回一个包含Class对象的数组,该Class对象代表所有公共类和接口,这些公共类和接口都是所表示的类对象的成员。
  • getComponentType()
    -返回表示数组的组件类型(即int,等类型)的类。
  • newInstance()
    -获取数组的新实例。

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

    //get the class type of the original array we passed in and determine the type, store in arrayTypeClass<?> 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 originalT[] copy = (T[])java.lang.reflect.Array.newInstance(arrayType, original.length);//Use System and arraycopy to copy the arraySystem.arraycopy(original, 0, copy, 0, original.length);return copy;

    }



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/438392.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号