Recently, the company's project required exporting a csv file. A colleague used the most primitive method to extract each record and add "," to solve the problem.
But the customer later requested that this function be added to every page. So, the problem comes, there are too many codes written separately, and together they cannot determine which object is stored in the list, and cannot use the get method to obtain attributes.
I always thought that when he wrote it like that, he wrote the program to death. However, after many attempts, the object was still taken out from the list through java reflection, and the attribute value was taken out from the object:
The following is the code:
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("111", "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)); } } } }
In this way, I don’t know where to start. When removing an object from the list, you can also get the attribute value of the object. You can write a public method to pass in the List object, and then generate and export the csv file.
For more java methods to take out objects from the list and obtain their attribute values, please pay attention to the PHP Chinese website!