数组的反射

写出通用的输出方法:

1. 数组类型,将元素逐个输出

2. 其他类型直接输出

 1 public static void printObject(Object obj) {
 2     Class clazz = obj.getClass();
 3     
 4     if(clazz.isArray()) {
 5         int len = Array.getLength(obj);    // java.lang.reflect.Array
 6         for(int i = 0; i < len; i++)
 7             System.out.print(Array.get(obj, i) + " ");
 8         System.out.println();
 9     }
10     else
11         System.out.println(obj);
12 }

注意:数组只有在元素类型相同、维度也相同时,类型才相同。

  new int[3].getClass() == new int[4].getClass()

  new int[3].getClass() != new int[3][1].getClass()

原文地址:https://www.cnblogs.com/joshua-aw/p/6020903.html