Java methods for extracting objects from a list and obtaining their property values _java

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.