Java method to fetch an object from a list and get its property values

  • 2020-04-01 02:30:51
  • OfStack

A recent company project required the export of CSV files. A colleague took out each record in the most primitive way and added ", "to solve the problem.
However, the client later requested that this feature be added to every page. The problem, then, is that there's too much code to write separately, and together you can't determine which object is stored in the list, and you can't get the properties using the get method.
I always thought he killed the program by writing it that way. However, after several attempts, the object was removed from the list by Java reflection, and the property value was removed from the object:

Here 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, when we do not know what object is taken from the list, we can also get the property value of the object, so we can write a public method to pass in the list object, and then generate the CSV file and export it.


Related articles: