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.