Found the problem

We all know that the Array class in the java.lang. Reflect package allows arrays to be created dynamically. We also know that Arrays’ copyOf() extends the array length. So how do you implement this generic approach?

Let’s say we now have a Person[] array A, and suddenly the problem feels solved by thinking that Person[] can be converted to Object[]. I wrote the following code:

/ * * *@paramA Source array *@paramNewLength New array length */
public static object[] badCopyOf(Object[] a, int newLength){
    var newArray = new Object[newLength];
    System.arrayCopy(a, 0, newArray, 0, Math.min(a.length, newLength));
    return newArray;
}
Copy the code

The cast is then returned, but a ClassCastException is reported, which means that the cast cannot be cast from Object[] to Person[]. This is a problem and can cause security problems if used elsewhere. So that’s not going to work.

To solve the problem

We thought of the Array static method newInstance to construct arrays.

Array.newInstance(ComponentType componentType, int newLength);

The first argument is the array content type, and the second argument is the length of the new array. So we need to do two things:

  1. Get the Class object of A, determine that A is an array, and then get the content type of A
  2. Get the source array length and newLength comparison.

The code is as follows:

public static Object goodCopyOf(Object a, int newLength){
    Class class = a.getClass();
    if(! class.isArray())return null;
    Class componentType = class.getComponetType();
    int length = Array.getLength(a);
    Object newArray = Array.newInstance(componentType, newLength);
    System.ArrayCopy(a, 0, newArray, 0, Math.min(length, newLength));
    return newArrary;
}
Copy the code

Array.newInstance builds arrays from ComponetType, so the Array type returned is the Array type of parameter A. Some of you might ask, “Hey, badCopyOf returns Object[] and good returns Object. What’s so special about that?” If you think about it, the base array is not a subclass of Object[], but is a subclass of Object, so Object is used for better applicability.