Java数组的反射

2016-12-25  本文已影响0人  Josaber

举个栗子来说明,写出通用的输出方法:

  1. 数组类型,将元素逐个输出
  2. 其他类型直接输出
public static void printObject(Object obj) {
    Class clazz = obj.getClass();
    
    if(clazz.isArray()) {
        int len = Array.getLength(obj);    // java.lang.reflect.Array
        for(int i = 0; i < len; i++)
            System.out.print(Array.get(obj, i) + " ");
        System.out.println();
    }
    else
        System.out.println(obj);
}

注意:数组只有在元素类型相同、维度也相同时,类型才相同。
new int[3].getClass() == new int[4].getClass()
new int[3].getClass() != new int[3][1].getClass()

上一篇下一篇

猜你喜欢

热点阅读