I have a class that looks like this:
public class TrafficReportMapper implements RowMapper<TrafficReport> {
@Override
public TrafficReport mapRow(ResultSet rs, int rowNum) {
// Do something here
return new TrafficReport(....);
}
}
TrafficReport
is a POJO and I want to extend it with something like DayTrafficReport
and to create a new mapper that extends TrafficReportMapper
. So I changed TrafficReportMapper
as follows:
public class TrafficReportMapper<T extends TrafficReport> implements RowMapper<T> {
@Override
public T mapRow(ResultSet rs, int rowNum) {
// Exactly the same code as before
return new TrafficReport(....);
}
}
Only this time I get
Incompatible Types: Required T; found TrafficReport
But the thing is that TrafficReport
must be of type T
. I'm not sure what I'm missing here.
You can declare your class
as follows:
public class TrafficReportMapper<T extends TrafficReport> implements RowMapper<TrafficReport>
... assuming:
interface RowMapper<T> {
public T mapRow(ResultSet rs, int rowNum);
...
}
Then if you have:
class TrafficReport{}
...and...
class DayTrafficReport extends TrafficReport{}
You can initialize as such:
TrafficReportMapper<DayTrafficReport> trm = new TrafficReportMapper<DayTrafficReport>();
If you create TrafficReportMapper<DayTrafficReport>
your method will become:
@Override
public DayTrafficReport mapRow(ResultSet rs, int rowNum) {
return new TrafficReport(....);
}
(not really since generics get erased, but it's a good way to think about it.)
But TrafficReport
is not a subtype of DayTrafficReport
, so you can't return it like this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.