There are requirements in the project to export data to a CSV file, because different classes have different properties, in order to code simple, the application of Java generics and reflection, wrote a function to complete the export function.
Public<T>voidSaveFile (list<t>list, String outFile) throws IOException {if(List = =NULL||List.isEmpty ()) { return; } if(Stringutils.isempty (outFile)) {Throw NewIllegalArgumentException ("outfile is null"); } Boolean IsFirst=true; BufferedWriter out=NULL; Try { out=NewBufferedWriter (NewFileWriter (outFile)); for(T t:list) {StringBuilder sb1=NewStringBuilder (); StringBuilder SB2=NewStringBuilder (); Class Clazz=(Class) T.getclass (); Field[] FS=Clazz.getdeclaredfields (); for(inti =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) {ThrowE1; } finally { Try { if( out!=NULL) { out. Close (); } } Catch(IOException E2) {ThrowE2; } } }
To export a CSV file by applying Java Generics and reflection