Sairam Vinjamuri
Sairam Vinjamuri

Reputation: 35

How to change an object's generic type dynamically in Java?

My Spring batch code reads and writes data to Database. I have two batch job classes and both the jobs have reader logics (almost same) with different pojo generic type (like Pojo1 and Pojo2) at below reader object.

FlatFileItemReader<DifferentPojoName> reader = new FlatFileItemReader<>();

Now I would like to create a generic reader logic in a separate @Component class. So that both the job classes will make use same reader logic.

But question is how can I change the Pojo type dynamically there in the reader object?

Please suggest.

Upvotes: 1

Views: 560

Answers (1)

davidxxx
davidxxx

Reputation: 131486

How to change an object's generic type dynamically in Java?

Generics are compilation features to improve the code typesafety.
so it is just not possible.

The cleaner way would be to declare distinct FlatFileItemReader beans with the generic it needs.
The @Bean annotation may be helpful there.

@Bean
public FlatFileItemReader<Foo> readerFoo(){
  return new FlatFileItemReader<>();
}

@Bean
public FlatFileItemReader<Bar> readerBar(){
  return new FlatFileItemReader<>();
}

And now inject them where you need :

@Autowired
FlatFileItemReader<Bar> readerBar;

@Autowired
FlatFileItemReader<Foo> readerFoo;

Upvotes: 3

Related Questions