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 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.
More info: What is reflection and why is it useful?
Syntax that may be unfamiliar
Class<?>
is using a wildcard operator
?
which basically says that we can have a
Class
object of unknown type - a generic version of class
Class
.
<T>
is a generic operator that stands for
raw type
Array
The Array class provides static methods to dynamically create and access Java arrays. i.e. This class contains methods that allow you to set and query the values of array elements, determine the length of the array, and create new instances of arrays. We are going to use
Array.newInstance()
Methods from reflection API
getClass ()
- returns an array containing Class objects representing all public classes and interfaces that are members of the represented class object.
getComponentType()
- returns the class representing the component type (what type i.e. int, , etc) of the array.
newInstance()
- Gets a new instance of an array.
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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…