Reflection of an array in java

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".
You have a large number of bad coding practices. Why would anyone give you the task to work on something that is rather abstract as this (accessing classes and fields and whatnot, then analyzing them) if you're fairly new to java? For example, you can initialise a String by just assigning a value. I think the exception is thrown because C is not an array at that moment but a field. Try casting it into an array... But idk how. You're bothering with abstract stuff that is pretty useless imo.

以上就是Reflection of an array in java的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏