Recent company projects need to export CSV file, a colleague in the most original way to remove each record and then add "," to solve.
But the customer later requires that this feature be added to each page. As a result, the problem is that there are too many separate writing codes, and it is not possible to determine which object is stored in the list, and you cannot get the property with the Getting method.
I always thought he wrote the program dead when he wrote it like that. However, after many attempts, the object was fetched from the list by Java reflection, and the attribute value was fetched from the object:
Here's the code:
Copy Code code as follows:
Package com.hb.test;
Import Java.lang.reflect.Field;
Import java.util.ArrayList;
Import java.util.List;
public class Test {
public static void Main (string[] args) throws IllegalArgumentException,
Exception {
person P1 = new Person ("a", "AAA");
person P2 = new Person ("222", "BBB");
List List = new ArrayList ();
List.add (p1);
List.add (p2);
Test (list);
}
public static void Test (List list) throws Exception, Illegalaccessexception {
for (int i = 0; i < list.size (); i++) {
field[] fields = List.get (i) getclass (). Getdeclaredfields ();
Object oi = list.get (i);
for (int j = 0; J < Fields.length; J + +) {
if (!fields[j].isaccessible ()) {
Fields[j].setaccessible (TRUE);
}
System.out.println (Fields[j].get (OI));
}
}
}
}
So when you do not know the object from the list, you can also get the object's attribute value, you can write a public way to pass in the list object, and then the CSV file generation, export.