簡體   English   中英

如何重構返回不同類型列表的方法

[英]How can I refactor methods that return different types of List

我有四種方法在做非常相似的事情。 他們讀取一個 CSV 文件並返回一個列表,但類型不同。 我想重構它們,但我不知道該怎么做。 也許有人可以幫忙。

這是我的代碼:

public List<PersonFirstName> readPersonFirstNames(Path path) throws FileNotFoundException {

    FileReader reader = new FileReader(path.toString());
    CsvToBean<PersonFirstName> csvToBean = new CsvToBeanBuilder<PersonFirstName>(reader)
            .withType(PersonFirstName.class)
            .withSeparator(';')
            .build();

    return csvToBean.parse();
}

public List<Street> readStreets(Path path) throws FileNotFoundException {

    FileReader reader = new FileReader(path.toString());
    CsvToBean<Street> csvToBean = new CsvToBeanBuilder<Street>(reader)
            .withType(Street.class)
            .withSeparator(';')
            .build();

    return csvToBean.parse();
}

public List<City> readCities(Path path) throws FileNotFoundException {

    FileReader reader = new FileReader(path.toString());
    CsvToBean<City> csvToBean = new CsvToBeanBuilder<City>(reader)
            .withType(City.class)
            .withSeparator(';')
            .build();

    return csvToBean.parse();
}

public List<PersonLastName> readPersonLastNames(Path path) throws FileNotFoundException {

    FileReader reader = new FileReader(path.toString());
    CsvToBean<PersonLastName> csvToBean = new CsvToBeanBuilder<PersonLastName>(reader)
            .withType(PersonLastName.class)
            .withSeparator(';')
            .build();

    return csvToBean.parse();
}
public <T> List<T> read(Path path, Class<T> clazz) throws FileNotFoundException {
    FileReader reader = new FileReader(path.toString());
    CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(reader)
            .withType(clazz)
            .withSeparator(';')
            .build();

    return csvToBean.parse();
}

該方法共享通用的讀取邏輯,並接受結果類型的類作為附加參數。

用法示例:

public List<PersonFirstName> readPersonFirstNames(Path path) throws FileNotFoundException {
    return read(path, PersonFirstName.class);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM