java.lang.reflect.Array类提供了动态创建和访问数组元素的各种
静态方法。
(一) 创建一维数组并赋值
package com.test.reflection;
import java.lang.reflect.Array;
public class ArrayTesterOne {
public static void main(String[] args) throws Exception {
Class<?> classType = Class.forName("java.lang.String");
Object array = Array.newInstance(classType, 10);
Array.set(array, 5, "hello");
String s = (String) Array.get(array, 5);
System.out.println(s);
}
}
(二)创建三维数组并赋值
package com.test.reflection;
import java.lang.reflect.Array;
public class ArrayTesterTwo {
public static void main(String[] args) throws Exception {
int[] dimensions = new int[] {5, 10, 15};
Object array = Array.newInstance(Integer.TYPE, dimensions);
Object array1 = Array.get(array, 3);
Object array2 = Array.get(array1, 5);
//result: class [[I
System.out.println(array.getClass().getComponentType());
//result: class [I
System.out.println(array1.getClass().getComponentType());
//result: int
System.out.println(array2.getClass().getComponentType());
Array.set(array2, 10, 37);
int[][][] value = (int[][][])array;
System.out.println(value[3][5][10]);
}
}