Spring Batch reader using generics

拈花ヽ惹草 提交于 2020-01-25 18:24:27

问题


I'm just new in the spring architecture and I am wondering if it is possible to use a generic T (o what you want) in an ItemStreamReader.

Something like this:

public class Reader implements ItemStreamReader<T extends SomeClass>{
    public T read() {
    .......
    }
    public void open() {
    .......
    }
    public void update() {
    .......
    }
    public void close() {
    .......
    }
}

So I pass to the reader various objects that extends SomeClass.


回答1:


this should work:

public class Reader<T extends SomeClass> implements ItemStreamReader<T>{
    public T read() {
    .......
    }
    public void open() {
    .......
    }
    public void update() {
    .......
    }
    public void close() {
    .......
    }
}

use it like:

Reader<SomeClass> reader = new Reader<>();
Reader<ExtendedFromSomeClass> reader2 = new Reader<>();



回答2:


I recommend you to read first about java generics.

http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#What is a parameterized (or generic) type?

But if you define your class

public class Reader implements ItemStreamReader<SomeClass>{
    public SomeClass read() {
    .......
    }
    public void open() {
    .......
    }
    public void update() {
    .......
    }
    public void close() {
    .......
    }
}

Your method can return any object that is Subclass of SomeClass.

For example

Reader a = new Reader();
Subclass b = (Subclass)a.read();


来源:https://stackoverflow.com/questions/33627388/spring-batch-reader-using-generics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!