Search code examples
java-7apache-commons-csv

Java - Generic class extended by concrete class


I have a number of classes, POJO style, that shares a single functionality, say readCSV method. So I want to use a single parent (or maybe abstract, not sure if it should be) class that these POJOs can extend. Here's a pseudo-code:

(abstract) class CSVUtil {

    private String[] fileHeader = null;

    protected void setFileHeader(fileHeader) {
        this.fileHeader = fileHeader;
    }

    protected List<WhateverChildClass> readCSV(String fileName) {

        // read CSV using Apache Commons CSV
        // and return a List of child type

        List<WhateverChildClass> list = null;
        // some declarations

        try {

            list = new ArrayList<WhateverChildClass>();

            csvParser = new CSVParser(fileReader, csvFormat);

            List csvRecords = csvParser.getRecords();

            for (...) {
                CSVRecord record = (CSVRecord) csvRecords.get(i);

                WhateverChildClass childClass = new WhateverChildClass();

                // loop through fields of childClass using reflection and assign
                for (// all fields of childClass) { 
                    childClass.setWhateverField(record.get(fileHeader[i]));
                }

                list.add(childClass);

                System.out.println(p);
                ps.add(p);
            }
        }
        ...

        return list;
    }
}

on one of the child classes, say ChildA

class ChildA extends CSVUtil {

    // fields, getters, setters

}

How do I code the CSVUtil such that I can determine in runtime the child class in readCSV defined in the parent class?

Is it possible to make this method static and still be inherited?

As an alternative, is there API in Apache Commons CSV that can generally read a CSV, determine its schema, and wrap it as a generic Object (I don't know if I make sense here), and return a list of whatever that Object is ?


Solution

  • You want that readCSV to be a static method ?

    Then, i would say that ChildA class shouldn't inherit from CSVUtil, but implement an Interface ... something like that :

    public final class CSVUtil {
    
      private CSVUtil() {
      }
    
      public static <T extends ICSV> List<T> readCSV(String filename) {
        ...
      }
    
    
    class ChildA implements ICSV