猿问

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

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


我想知道有没有一种方法可以在一个常见的地方实现这个方法,这样我的每个文件都会调用这个方法来配置我的阅读器来读取它们相应的文件。


每个文件都会发送不同的实体类来加载它们的文件。像主要实体、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);

}


qq_遁去的一_1
浏览 147回答 1
1回答

守候你守候我

向方法中添加泛型private <T> void flatFileItemReaderConfig(FlatFileItemReader<T> flatFileReader, String fileName, String incomingHeader, Class<T> clazz) {&nbsp; &nbsp; // set delimiter as '|'&nbsp; &nbsp; DefaultLineMapper<T> defaultLineMapper = new DefaultLineMapper<>();&nbsp; &nbsp; DelimitedLineTokenizer delimitedLineTokenizer = new DelimitedLineTokenizer("|");&nbsp; &nbsp; delimitedLineTokenizer.setNames(convertHeaderToEntityAttrib(fileName, incomingHeader));&nbsp; &nbsp; defaultLineMapper.setLineTokenizer(delimitedLineTokenizer);&nbsp; &nbsp; // convert each record into primary entity&nbsp; &nbsp; BeanWrapperFieldSetMapper<T> beanWrapperFieldSetMapper = new BeanWrapperFieldSetMapper<>();&nbsp; &nbsp; beanWrapperFieldSetMapper.setTargetType(clazz);&nbsp; &nbsp; beanWrapperFieldSetMapper.setCustomEditors(getCustomFormatters());&nbsp; &nbsp; defaultLineMapper.setFieldSetMapper(beanWrapperFieldSetMapper);&nbsp; &nbsp; flatFileReader.setLineMapper(defaultLineMapper);}如果您只想将使用限制为列出的实体,请创建一个由所有具体实体 ( PrimaryEntity, ChildEntity1, ChildEntity2, ChildEntity3, ChildEntity4) 实现的通用接口实体,并将签名更改为private <T extends Entity> void flatFileItemReaderConfig(...)
随时随地看视频慕课网APP

相关分类

Java
我要回答