下方法源码详解

时间:2025-04-08 08:06:08

如果判断为真,即原数组是Object类型数组,则直接创建一个给定长度newLength的新的Object数组即可.(为什么要创建新数组呢?因为这个函数目的就是复制一个数组的指定部分到一个新数组.)

如果判断为假,即原数组不是Object类型数组,则调用**(T[]) Array.newInstance((), newLength)**这个方法是新建一个数组,数组类型为newType中元素的类型(默认返回Object类型,可强制转换为正确类型,详情看下列代码示例),长度为指定的newLength.


public native Class<?> getComponentType();
  • 1

本地方法,返回数组内的元素类型,不是数组时,返回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

创建一个类型与newType一样,长度为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返回为Object,实质为数组

public class SystemArrayCopy {

    public static void main(String[] args) {
        Object o = (, 10);
        (());
        (); // 用于对比
    }
}
/*
class [;
class 
*/
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

可以看到,的返回虽然是Object类型,但是它实质上是String数组,可以强制转换成String[],如:String[] arr = (String[]) (, 10);