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

    在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;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值