Methods for exporting CSV files using Java generics and reflection _java

Source: Internet
Author: User

This example describes how to apply Java Generics and reflection to export a CSV file. Share to everyone for your reference. Specifically as follows:

There is a need in the project to export the data as a CSV file, because different classes have different attributes, in order to code simple, Java generics and reflection, write a function, complete the export function.

Copy Code code as follows:
Public <T> void SaveFile (list<t> List, String outfile) throws IOException {
if (list = = NULL | | list.isempty ()) {
Return
}
if (Stringutils.isempty (outfile)) {
throw new IllegalArgumentException ("outfile is null");
}
Boolean isfirst = true;
BufferedWriter out = null;
try {
out = new BufferedWriter (new FileWriter (outfile));
for (T t:list) {
StringBuilder sb1 = new StringBuilder ();
StringBuilder SB2 = new StringBuilder ();
Class Clazz = (Class) T.getclass ();
field[] fs = Clazz.getdeclaredfields ();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
F.setaccessible (TRUE);
try {
if (Isfirst) {
Sb1.append (F.getname ());
Sb1.append (",");
}
Object val = f.get (t);
if (val = = null) {
Sb2.append ("");
} else {
Sb2.append (Val.tostring ());
}
Sb2.append (",");
catch (IllegalArgumentException | Illegalaccessexception e) {
E.printstacktrace ();
}
}
if (Isfirst) {
Out.write (Sb1.tostring ());
Isfirst = false;
Out.newline ();
}
Out.write (Sb2.tostring ());
Out.newline ();
}
catch (IOException E1) {
Throw E1;
finally {
try {
if (out!= null) {
Out.close ();
}
catch (IOException E2) {
throw E2;
}
}
}

I hope this article will help you with your Java programming.

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.