If it is judged to be true, that is, the original array is an Object type array, then directly create a new Object array of newLength of the given length. (Why do you need to create a new array? Because thisfunctionThe purpose is to copy the specified part of an array to a new array.)
If it is judged as false, that is, the original array is not an Object type array, then **(T[])Array.newInstance((), newLength)**This method is to create a new array, the array type is the type of the element in newType (the default returns the Object type, which can be cast to the correct type. See the following code example for details), and the length is the specified newLength.
public native Class<?> getComponentType();
- 1
Local method returns the element type in the array. When it is not an array, it returns null
public class SystemArrayCopy {
public static void main(String[] args) {
String[] o = {"aa", "bb", "cc"};
System.out.println(o.getClass().getComponentType());
System.out.println(Object.class.getComponentType());
}
}
/*
class
null
*/
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
private static native Object newArray(Class<?> componentType, int length)
throws NegativeArraySizeException;
- 1
- 2
Create an array of type the same as newType and length newLength
public static Object newInstance(Class<?> componentType, int length)
throws NegativeArraySizeException {
return newArray(componentType, length);
}
private static native Object newArray(Class<?> componentType, int length)
throws NegativeArraySizeException;
- 1
- 2
- 3
- 4
- 5
- 6
newInstance returns as Object, essentially an array
public class SystemArrayCopy {
public static void main(String[] args) {
Object o = (, 10);
(());
(); // for comparison
}
}
/*
class [;
class
*/
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
You can see that although the return is of Object type, it is essentiallyStringArrays can be cast to String[], such as: String[] arr = (String[]) (, 10);