如何在 java 中以通用方式编写此方法

How to write this method in a generic way in java

目前,我已经为五个不同的 class 实施了此方法,以便为五个不同的文本文件配置 FlatFileReader 并加载到数据库中 table。

我想知道有没有办法在一个普通的地方实现这个方法,这样我的每个文件都会调用这个方法来配置我的reader来读取它们对应的文件..

每个文件都会发送不同的实体class来加载它们的文件。像主要实体、ChildEntity1、ChildEntity2、ChildEntity3、ChildEntity4。

private void flatFileItemReaderConfig(FlatFileItemReader<PrimaryEntity> flatFileReader,
        String fileName, String incomingHeader)
{
    // set delimiter as '|'
    DefaultLineMapper<PrimaryEntity> defaultLineMapper = new DefaultLineMapper<>();

    DelimitedLineTokenizer delimitedLineTokenizer = new DelimitedLineTokenizer("|");
    delimitedLineTokenizer.setNames(convertHeaderToEntityAttrib(fileName, incomingHeader));
    defaultLineMapper.setLineTokenizer(delimitedLineTokenizer);

    // convert each record into primaryentity
    BeanWrapperFieldSetMapper<PrimaryEntity> beanWrapperFieldSetMapper = new BeanWrapperFieldSetMapper<>();
    beanWrapperFieldSetMapper.setTargetType(PrimaryEntity.class);
    beanWrapperFieldSetMapper.setCustomEditors(getCustomFormatters());

    defaultLineMapper.setFieldSetMapper(beanWrapperFieldSetMapper);

    flatFileReader.setLineMapper(defaultLineMapper);
}

向方法添加泛型

private <T> void flatFileItemReaderConfig(FlatFileItemReader<T> flatFileReader, String fileName, String incomingHeader, Class<T> clazz) {

    // set delimiter as '|'
    DefaultLineMapper<T> defaultLineMapper = new DefaultLineMapper<>();

    DelimitedLineTokenizer delimitedLineTokenizer = new DelimitedLineTokenizer("|");
    delimitedLineTokenizer.setNames(convertHeaderToEntityAttrib(fileName, incomingHeader));
    defaultLineMapper.setLineTokenizer(delimitedLineTokenizer);

    // convert each record into primary entity
    BeanWrapperFieldSetMapper<T> beanWrapperFieldSetMapper = new BeanWrapperFieldSetMapper<>();
    beanWrapperFieldSetMapper.setTargetType(clazz);
    beanWrapperFieldSetMapper.setCustomEditors(getCustomFormatters());
    defaultLineMapper.setFieldSetMapper(beanWrapperFieldSetMapper);
    flatFileReader.setLineMapper(defaultLineMapper);
}

如果您只想将使用限制在列出的实体中,请创建一个由所有具体实体 (PrimaryEntity, ChildEntity1, ChildEntity2, ChildEntity3, ChildEntity4) 实现的通用接口实体,并将签名更改为

private <T extends Entity> void flatFileItemReaderConfig(...)