Extended array Length Using Reflection, reflected array Length
Extended array Length Using Reflection
Idea: to extend the array length is actually to generate a new array to overwrite the old array.
Import java. lang. reflect. *; public class Answer {public static void main (String [] args) {Test test = new Test (); test. print (); // print the content of the array test. is = (int []) addArrayLength (test. is, 10); // overwrite the old array test with the new array. ss = (String []) addArrayLength (test. ss, 10); test. print ();} public static Object addArrayLength (Object array, int newLength) {Object newArray = null; Class componentType = array. getClass (). getComponentType (); // obtain the class Object newArray = Array of an Array. newInstance (componentType, newLength); // dynamically creates an array System. arraycopy (array, 0, newArray, 0, Array. getLength (array); // returns newArray;} class Test {public int [] is = {1, 2, 3 }; public String [] ss = {"A", "B", "C"}; public void print () {for (int index = 0; index <is. length; index ++) {System. out. println ("is [" + index + "] =" + is [index]);} System. out. println (); for (int index = 0; index <ss. length; index ++) {System. out. println ("ss [" + index + "] =" + ss [index]);} System. out. println ();}}
Note:
Array. getClass (). getComponentType () to get an array class Object
Array. newInstance (componentType, newLength) dynamically creates an Array of the specified type
System. arraycopy (array, 0, newArray, 0, Array. getLength (array) implements copying between arrays. These five parameters represent the copied array, starting position, copying array, starting position, and length.