java反射笔记四

来源:互联网 发布:苹果办公软件下载 编辑:程序博客网 时间:2024/06/05 19:35

数组的反射

类:java.lang.reflect.Array

利用数组的反射实现数组的可变长度

/** *按10%的速度增长  * @param array * @return */public static Object arrayGrow(Object array) {Class<?> clazz = array.getClass();if(!clazz.isArray()) {return null;}Class<?> componentType = clazz.getComponentType();int length = Array.getLength(array);int newLength = length * 11/10 + 10;Object newArray = Array.newInstance(componentType, newLength);System.arraycopy(array, 0, newArray, 0, length);return newArray;}

利用反射遍历数组元素

/** * 利用反射遍历数组 * @param array */public static void arrayPrint(Object array) {Class<?> clazz = array.getClass();if(!clazz.isArray()) {return;}Class<?> componentType = clazz.getComponentType();int length = Array.getLength(array);System.out.print(componentType + "[" + length + "] {");for(int x = 0; x < length; x++) {if(x == length-1) {System.out.print(Array.get(array, x));} else {System.out.print(Array.get(array, x) + ",");}}System.out.println("}");}

Array中部分API说明

static Object get(Object array, int index)
static xxx getXxx(Object array, int index)
返回指定位置上的数组的指定内容(xxx代表的是8中基本数据类型中的一种)
static int getLength(Object array)
返回数组的长度
static Object newInstance(Class<?> componentType, int length)
static Object newInstance(Class<?> componentType, int[] length)
返回一个给定维数,给定维数的新数组


0 0
原创粉丝点击