Java源码分析——java.lang.reflect反射包解析(二) Array类,数组的创建

版权声明:博主GitHub地址https://github.com/suyeq欢迎大家前来交流学习 https://blog.csdn.net/hackersuye/article/details/83542168

    在Java中,引用类型中有那么几个特殊的类,Object类是所有类的起源、Class类定义所有类的抽象与行为、ClassLoader类实现了类从.class文件中加载进jvm,而Array数组类,则实现了数组手动的创建。

    Array数组类,是个不可被继承的类:

public final
class Array {
    private Array() {}

    而且构造方法是私有的,不能直接创建该类,其中有两种创造数组的方法,第一种格式如下:

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;

    它调用的newArray是native方法,它接受两个参数,一个Class类对象表明数组存贮的内容,另外一个表明数组的长度。如下面示例代码:

public  class Test {
    public static void main(String args[]) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        int []test= (int[]) Array.newInstance(int.class,10);
        for (int i=0;i<test.length;i++){
            test[i]=1;
        }
        for (int i=0;i<test.length;i++){
            System.out.print(test[i]+" ");
        }
}

//输出为:1 1 1 1 1 1 1 1 1 1

    另外一种格式是用来创造多维数组的,其源码如下:

public static Object newInstance(Class<?> componentType, int... dimensions)
        throws IllegalArgumentException, NegativeArraySizeException {
        return multiNewArray(componentType, dimensions);
    }

 private static native Object multiNewArray(Class<?> componentType,
        int[] dimensions)
        throws IllegalArgumentException, NegativeArraySizeException;

    它接受一个Class类对象,以及一个dimensions可变数组来输入的n维。比如创建一个二维数组,如下代码所示:

public class Test {
    public static void main(String args[]) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        int [][]test= (int[][]) Array.newInstance(int.class,2,2);
        for (int i=0;i<test.length;i++){
            for (int j=0;j<test[i].length;j++){
                test[i][j]=1;
            }
        }
        for (int i=0;i<test.length;i++){
            for (int j=0;j<test[i].length;j++){
                System.out.print(test[i][j]+" ");
            }
            System.out.println();
        }
    }
}

    剩余的几个重要的方法就不一一讲解了,在这里列出来:

//获取其数组长度
public static native int getLength(Object array)
        throws IllegalArgumentException;

 //获取指定索引的值      
 public static native Object get(Object array, int index)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

//设置指定索引的值
public static native void set(Object array, int index, Object value)
        throws IllegalArgumentException, ArrayIndexOutOfBoundsException;

猜你喜欢

转载自blog.csdn.net/hackersuye/article/details/83542168
今日推荐