简体   繁体   English

使用泛型时不兼容的类型

[英]Incompatible type when using generic

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 . TrafficReport是POJO,我想它的东西,如延长DayTrafficReport并创建扩展新的映射TrafficReportMapper So I changed TrafficReportMapper as follows: 因此,我将TrafficReportMapper更改如下:

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; 不兼容的类型:必填T; found TrafficReport 找到了TrafficReport

But the thing is that TrafficReport must be of type T . 但事实是, TrafficReport必须为T类型。 I'm not sure what I'm missing here. 我不确定我在这里缺少什么。

You can declare your class as follows: 您可以按以下方式声明您的class

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: 如果创建TrafficReportMapper<DayTrafficReport>方法将变为:

@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. 但是TrafficReport 不是一个亚型DayTrafficReport ,所以你不能这样回去。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM