To be able to select specific fields and order you should specifiy them i.e. by a list of field names.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.StringTokenizer;
public class CsvReflect {
int a = 10;
String b = "test";
Date d = new Date();
public int getA() {
return a;
}
public String getB() {
return b;
}
public Date getD() {
return d;
}
public static String toCsv(Object obj, String fields, String separator) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(fields,",");
while ( st.hasMoreElements() ) {
String field = st.nextToken();
Method getter = obj.getClass().getMethod("get"+ field, new Class[]{});
String val = "" + getter.invoke(obj, new Class[]{});
sb.append( val );
if ( st.hasMoreElements() ) {
sb.append(separator);
}
}
return sb.toString();
}
public static void main(String[] args) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
CsvReflect csv = new CsvReflect();
System.out.println( csv.toCsv( csv ,"A,B,D", "|" ));
}
}