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

时间:2019-08-13 10:28:27

标签: java java-8 spring-batch flatfilereader

当前,我为五个不同的类实现了此方法,以为五个不同的文本文件配置FlatFileReader并加载到数据库表中。

我想知道是否有一种方法可以在一个普通的地方实现此方法,以便我的每个文件都将调用此方法来配置我的阅读器以读取其相应的文件。

每个文件都会发送不同的实体类以加载其文件。像Primay Entity,ChildEntity1,ChildEntity2,ChildEntity3,ChildEntity4。

private void flatFileItemReaderConfig(FlatFileItemReader<PrimaryEntity> flatFileReader,
        String fileName, String incomingHeader)
{
// set delimitter 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);
}

1 个答案:

答案 0 :(得分:4)

将泛型添加到方法中

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

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

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

    // convert each record into primaryentity
    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(...)