问题描述
对于我的编程任务,我被要求编写一个通用的复制方法来从一个数组复制到一个相同大小和类型的数组.这在Java中甚至可能吗?我尝试的一切都以一些通用数组创建"错误告终.我迷路了,不知道如何解决这个问题!
For my programming assignment, I was asked to write a generic copy method to copy from one array to an identically sized and typed array. Is this even possible in Java? Everything I tried ended up with some "generic array creation" error. I am lost and don't know how to solve this problem!
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]; } }
推荐答案
可以使用反射的概念编写一个可以在运行时判断类型的泛型复制方法.简而言之,反射是在运行时检查类、接口、字段和方法的能力,而无需在编译时知道类、方法等的名称.
You can use the concept of reflection to write a generic copy method that can determine type at runtime. In a nutshell, reflection is the ability to inspect classes, interfaces, fields and methods at runtime without knowing the names of classes, methods etc at compile time.
java.lang.Reflect 与 java.lang.Class 组成 Java 反射 API.这个方法使用这两个类和它们的一些方法来创建一个通用的 arrayCopy 方法,它将为我们找出类型.
java.lang.Reflect together with java.lang.Class comprise the Java Reflection API. This method uses both of those classes and some of their methods to make a generic arrayCopy method that will find out the type for us.
更多信息:什么是反射,为什么它有用?
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, 0, copy, 0, original.length); return copy; }