Reflection of an array in java

2019-07-28 02:56发布

I'm fairly new to java and have come across a problem. My task is to create a class which contains a method write(Object obj) that writes the type of the object as well as the name and type of all attributes into a file. Recursion is involved since the object may have objects/arrays of objects as attributes.

Here is the code:

    public void write(Object obj) throws Exception {

    if(obj == null)
    {
        out.close();
        return;
    }

    Class c = obj.getClass();
    Class d;
    Field fields_c[] = c.getDeclaredFields();
    System.out.println("class_name:" + c.getName());

    int i, j;
    String tab = new String("");


    for(i = 0; i < indent_level; i++)
    {
        tab = tab + "\t";
    }

    out.write(tab + "class_name:" + c.getName() + "\n");

    for(i = 0; i < fields_c.length; i++) {
        System.out.println("field name: " + fields_c[i].getName() + " ");

        c = fields_c[i].getType();
        fields_c[i].setAccessible(true);

        if(c.isPrimitive()) {
            out.write("\t" + tab + "field_name:" + c.toString() + "\n");
        }
        else if(c.isArray()) {
            System.out.println("field of type array with elements of type:" + c.getComponentType());

            for(j = 0; j < Array.getLength(c); j++)
            {
                d = Array.get(c, j).getClass();
                indent_level = indent_level + 1;
                this.write(d);
                indent_level = indent_level - 1;            
            }
        }
        else
        {
            System.out.println("field is not primitive of type:" + c.getName());
            Object foo = fields_c[i].get(obj);
            indent_level = indent_level + 1;
            this.write(foo);
            indent_level = indent_level - 1;
        }
    }
}

An exception arises if I call the method and give an Object that has an array attribute; all attributes until the array are written properly to the output file. The exception is "java.lang.IllegalArgumentException: Argument is not an array".

3条回答
相关推荐>>
2楼-- · 2019-07-28 03:13

In d = Array.get(c, j).getClass(); c is of type java.lang.Class, but an array is expected.

You should change it to d = Array.get(fields_c[i].get(obj), j) and use c#getComponentType for get the type of the array.

查看更多
可以哭但决不认输i
3楼-- · 2019-07-28 03:14

Why you're passing Class of elements instead of elements:

        Object[] array = fields_c[i].get(obj);
        for(j = 0; j < Array.getLength(array); j++)
        {
            Object foo = Array.get(array, j); // not .getClass()
            indent_level = indent_level + 1;
            this.write(foo);
            indent_level = indent_level - 1;            
        }
查看更多
霸刀☆藐视天下
4楼-- · 2019-07-28 03:33

This may not be what you're after, but if this is to do with serialisation then I recommend "Simple";

http://simple.sourceforge.net/

It makes Java <=> XML serialisation unbelievably easy.

查看更多
登录 后发表回答