美文网首页
Java数组的反射

Java数组的反射

作者: Josaber | 来源:发表于2016-12-25 12:43 被阅读0次

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

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

    相关文章

      网友评论

          本文标题:Java数组的反射

          本文链接:https://www.haomeiwen.com/subject/pvorvttx.html