How do I get a class instance of generic type T?

前端 未结 22 1257
猫巷女王i
猫巷女王i 2020-11-21 11:03

I have a generics class, Foo. In a method of Foo, I want to get the class instance of type T, but I just can\'t call T.

22条回答
  •  长情又很酷
    2020-11-21 11:43

    I wanted to pass T.class to a method which make use of Generics

    The method readFile reads a .csv file specified by the fileName with fullpath. There can be csv files with different contents hence i need to pass the model file class so that i can get the appropriate objects. Since this is reading csv file i wanted to do in a generic way. For some reason or other none of the above solutions worked for me. I need to use Class type to make it work. I use opencsv library for parsing the CSV files.

    private List readFile(String fileName, Class type) {
    
        List dataList = new ArrayList();
        try {
            File file = new File(fileName);
    
            Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            Reader headerReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    
            CSVReader csvReader = new CSVReader(headerReader);
            // create csv bean reader
            CsvToBean csvToBean = new CsvToBeanBuilder(reader)
                    .withType(type)
                    .withIgnoreLeadingWhiteSpace(true)
                    .build();
    
            dataList = csvToBean.parse();
        }
        catch (Exception ex) {
            logger.error("Error: ", ex);
        }
    
        return dataList;
    }
    

    This is how the readFile method is called

    List rigSurfaceCSVDataList = readSurfaceFile(surfaceFileName, RigSurfaceCSV.class);
    

提交回复
热议问题