java – 编写复制数组的通用方法
对于我的编程任务,我被要求编写一个通用的复制方法,从一个数组复制到相同大小和类型的数组.这在
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的通用版本. 反射API的方法 > getClass() – 返回一个包含Class对象的数组,这些对象表示作为所表示的类对象成员的所有公共类和接口. 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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |