首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java中Array的反照

2012-08-22 
java中Array的反射java.lang.reflect包里面的类是做反射用的,其中Array是处理数组反射的,结合java.lang.Cl

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);


热点排行