I have a few objects stored in multiple CSV files, and would like to:
- Read the CSV file
- Create objects based on the read tokens
- Store and return the created objects into an arraylist.
Of course, creating separate functions for each object would be simple, but that would be tedious if I were to have a large number of objects to read in.
Is it possible to create a single function that is able to do all this dynamically?
Something like:
public ArrayList readFromCSV(String objectName){
//generic all in one code
}
or
public ArrayList readFromCSV(Class classItself){
//generic all in one code
}
Essentially I'm trying to do the opposite of the following:
public static void saveArray(String filename, List al) throws IOException {
List alw = new ArrayList();// to store Professors data
for (Object obj : al) {
try {
Class c = obj.getClass();
Field[] fields = c.getDeclaredFields();
int noOfFields = fields.length;
StringBuilder st = new StringBuilder();
for (int i = 0; i < noOfFields; i++) {
// System.out.println("The field is: " + fields[i].getName());
Field field = obj.getClass().getDeclaredField(fields[i].getName());
field.setAccessible(true);
Object value = field.get(obj);
st.append(value.toString().trim());
if (i != noOfFields - 1) {
st.append(SEPARATOR);
}
}
alw.add(st.toString());
write(filename, alw);
} catch (Exception e) {
System.out.println(e.toString());
}
}
}