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



