[java 反射] Array介绍

来源:互联网 发布:基因组数据库意义 编辑:程序博客网 时间:2024/06/07 17:14

简介

Array提供了一些静态方法来动态的创建和访问Java里的数组。
Array的set 和 get 操作允许向上转型,但向下转型会抛出IllegalArgumentException

构造方法

public static Object newInstance(Class<?> componentType, int length);

compoentType 代表数组的类型
length 为数组的长度
返回一个新数组
当指定的componentTypenull时,会抛出一个NullPointerException
如果componentTypeVoid类型 或者数组的维度大于255 会抛出 IllegalArgumentException
如果length负整数的话,会抛出NegativeArraySizeException

public static Object newInstance(Class<?> componentType, int length)   throws NegativeArraySizeException {   //内部其实调用了native方法    return newArray(componentType, length);}

例如:

final String[] arr = (String[]) Array.newInstance(String.class, 10);等价于final String[] arr = new String[10];

public static Object newInstance(Class<?> componentType, int... dimensions)
如果dimensions为空,则抛出IllegalArgumentException

public static Object newInstance(Class<?> componentType, int... dimensions)        throws IllegalArgumentException, NegativeArraySizeException {        //底层调用的multiNewArray本地方法        return multiNewArray(componentType, dimensions);    }
final String[][][] strs = (String[][][])Array.newInstance(String.class, 2, 3, 4);等价于:String[][][] strs = new String[2][3][4];

静态方法

public static native int getLength(Object array) throws IllegalArgumentException
返回指定数组对象的长度
如果给定的参数不是数组对象的话,抛出IllegalArgumentException

String[] strArr = new String[10];int len = Array.getLength(strArr);等价于int len = strArr.length;

public static native Object get(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException

返回指定数组对象的索引组件。返回的值会自动的包装成对象如果他是
原始类型

如果指定的对象是null,则抛出NullpointerException异常
如果指定的对象不是数组,则抛出IllegalArgumentException异常
如果指定的参数是负数,或者大于等于数组的长度,则抛出ArrayIndexOutOfBoundsException

String[] strArr = new String[10];String str = (String)Array.get(strArr, 0);等价于String str = strArr[0];

public static native void set(Object array, int index, Object value) throws IllegalArgumentException, ArrayIndexOutOfBoundsException;
设置指定数组对象的指定索引的新值,如果数组对象是基于原始类型的,则新值首先自动拆箱

下面省略一大堆set get方法
Array提供了例如对数组的初始化,访问,修改,获取数组的长度的基本操作。

0 0
原创粉丝点击