Step By Step(Java 反射篇) (四)

2014-11-24 03:19:38 · 作者: · 浏览: 13
public class MyTest {

2 public static void main(String[] args) {

3 Object o = new int[1][2][3];

4 System.out.println("The length is " + Array.getLength(o));

5 System.out.println("The Dimension is " + getDim(o));

6 }

7 public static int getDim(Object array) {

8 int dim = 0;

9 Class< > cls = array.getClass();

10 while (cls.isArray()) {

11 ++dim;

12 //getComponentType获取数组元素的Class对象,

13 //如果不是数组返回null。

14 cls = cls.getComponentType();

15 }

16 return dim;

17 }

18 }

19 /* 输出结果如下:

20 The length is 1

21 The Dimension is 3

22 */

5) 通过反射填充和显示数组元素:

1 public class MyTest {

2 public static void main(String args[]) {

3 Object array = Array.newInstance(int.class, 3);

4 fillArray(array);

5 displayArray(array);

6 }

7 private static void fillArray(Object array) {

8 //这里是通过反射的方式获取数组的长度,效率会低于

9 //通过数组对象的length方法获取,因此这里的例子缓存

10 //了该长度,而不是直接放到for循环的第二个表达式

11 int length = Array.getLength(array);

12 for (int i = 0; i < length; i++) {

13 //设置array数组的第i个元素的值为i*i。

14 Array.setInt(array, i, i*i);

15 }

16 }

17 private static void displayArray(Object array) {

18 int length = Array.getLength(array);

19 for (int i = 0; i < length; i++) {

20 //获取array数组的第i个元素,并返回int值。

21 int value = Array.getInt(array, i);

22 System.out.println("Position: " + i + ", value: " + value);

23 }

24 }

25 }

26 /* 输出结果如下:

27 Position: 0, value: 0

28 Position: 1, value: 1

29 Position: 2, value: 4

30 */

6) 基于数组对象再通过反射的机制创建一个相同的数组对象:

1 public class MyTest {

2 public static void main(String args[]) {

3 int[] ints = new int[2];

4 Object ret = buildNewArrayWithReflection(ints);

5 if (ret != null) {

6 Arrays.equals(ints, (int[])ret);

7 System.out.println("The both array are equal.");

8 }

9 }

10 private static Object buildNewArrayWithReflection(Object source) {

11 if (!source.getClass().isArray()) {

12 System.out.println("The argument is NOT an array.");

13 return null;

14 }

15 Class< > arrayClass = source.getClass();

16 String arrayName = arrayClass.getName();

17 Class< > componentClass = arrayClass.getComponentType();

18 String componentName = componentClass.getName();

19 System.out.println("Array: " + arrayName + ", Component: " + componentName);

20 int length = Array.getLength(source);

21 Object ret = Array.newInstance(componentClass, length);

22 System.arraycopy(source, 0, ret, 0, length);

23 return ret;

24 }

25 }

26 /* 输出结果如下:

27 Array: [I, Component: int

28 The both array are equal.

29 */

3. 基于对象域字段的反射:

1) 列出对象的public域字