Java 反射 Array动态创建数组
@author ixenos
注:java.lang.reflect.Array 是个反射工具包,全是静态方法,创建数组以多维数组为基准,一维数组只是特殊实现
创建一个具有指定的组件类型和长度的新数组(一维数组)
newInstance
public static Object newInstance(Class<?> componentType, int length) throws NegativeArraySizeException
创建一个具有指定的组件类型和长度的新数组。调用此方法等效于创建如下数组:
int[] x = {length}; //创建数组以多维数组为基准,一维数组只是特殊实现 Array.newInstance(componentType, x);
参数:
componentType - 表示新数组的组件类型的
Class 对象
length - 新数组的长度
返回:
新数组 抛出:
NullPointerException - 如果指定的
componentType 参数为 null
IllegalArgumentException - 如果 componentType 为
Void.TYPE
NegativeArraySizeException - 如果指定的
length 为负
创建一个具有指定的组件类型和维度的新数组(多维数组)
newInstance
public static Object newInstance(Class<?> componentType, int... dimensions) throws IllegalArgumentException, NegativeArraySizeException
创建一个具有指定的组件类型和维度的新数组。 如果 componentType 表示一个非数组类或接口,则新数组具有 dimensions.length 维度,并且将 componentType 作为其组件类型。
如果 componentType 表示一个数组类,则新数组的维数等于 dimensions.length 和 componentType 的维数的总和。在这种情况下,新数组的组件类型为
componentType 的组件类型。
新数组的维数不能超过该实现所支持的数组维数(通常为 255)。
参数:
componentType - 表示新数组的组件类型的
Class 对象
dimensions - 表示新数组维度的
int 数组
返回:
新数组 抛出:
NullPointerException - 如果指定的
componentType 参数为 null
IllegalArgumentException - 如果指定的
dimensions 参数是一个零维度的数组,或者所请求的维数超过了该实现所支持的数组维数的限制(通常为 225),或者度的数组,或者所请求的维数超过了该实现所支持的数组维数的限制(通常为 225),或者 componentType 为
Void.TYPE。
NegativeArraySizeException - 如果指定的
dimensions 参数中的任意组件为负。
创建多维数组示例:
//get(Object array, int index) 返回指定数组对象中索引组件的值
//setInt(Object array, int index, int i) 将指定数组对象中索引组件的值设置为指定的 int 值。