读书人

java中Array的反照

发布时间: 2012-08-22 09:50:34 作者: rapoo

java中Array的反射
java.lang.reflect包里面的类是做反射用的,其中Array是处理数组反射的,结合java.lang.Class类,可以在运行时知道数组的相关信息。

1. 判断传入的对象是不是数组

// obj is the instance passed in running timeboolean bArray = obj.getClass().isArray();


2. 拿到数组的长度

// obj is the instance passed in running timeint length = java.lang.reflect.Array.getLength(obj);


3. 迭代数组的元素

// obj is the instance passed in running timefor (int i = 0; i < len; i++) {  System.out.println(Array.get(obj, i));}


4. 判断数组元素的类型

// obj is the instance passed in running timeClass elementType = obj.getClass().getComponentType();


5. 实例化数组

如果知道数组的类型(如int类型),直接实例化int[] array = new int[4];
如果是运行时才知道类型,使用下面的方法:

// componentType - the Class object representing the component type of the new array// length - the length of the new arrayObject array = Array.newInstance(componentType, length);


读书人网 >编程

热点推荐