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".