Java 使用泛型时类型不兼容
我有一个类似这样的类:Java 使用泛型时类型不兼容,java,generics,Java,Generics,我有一个类似这样的类: public class TrafficReportMapper implements RowMapper<TrafficReport> { @Override public TrafficReport mapRow(ResultSet rs, int rowNum) { // Do something here return new TrafficReport(....); } } 只有这一次我得到了 不兼容类型:必
public class TrafficReportMapper implements RowMapper<TrafficReport> {
@Override
public TrafficReport mapRow(ResultSet rs, int rowNum) {
// Do something here
return new TrafficReport(....);
}
}
只有这一次我得到了
不兼容类型:必填T;找到流量报告
但问题是
TrafficReport
必须是T
类型。我不确定我错过了什么 您可以按如下方式声明您的类
:
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(....);
}
}
public class TrafficReportMapper<T extends TrafficReport> implements RowMapper<TrafficReport>
……还有
class DayTrafficReport extends TrafficReport{}
您可以这样初始化:
TrafficReportMapper<DayTrafficReport> trm = new TrafficReportMapper<DayTrafficReport>();
TrafficReportMapper trm=new 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(....);
}
}
public class TrafficReportMapper<T extends TrafficReport> implements RowMapper<TrafficReport>
……还有
class DayTrafficReport extends TrafficReport{}
您可以这样初始化:
TrafficReportMapper<DayTrafficReport> trm = new TrafficReportMapper<DayTrafficReport>();
TrafficReportMapper trm=new TrafficReportMapper();
如果您创建TrafficReportMapper
您的方法将变成:
@Override
public DayTrafficReport mapRow(ResultSet rs, int rowNum) {
return new TrafficReport(....);
}
(不是真的,因为泛型被删除了,但这是一个很好的思考方式。)
但是
TrafficReport
不是DayTrafficReport
的子类型,因此您不能这样返回它。如果您创建TrafficReportMapper
您的方法将变为:
@Override
public DayTrafficReport mapRow(ResultSet rs, int rowNum) {
return new TrafficReport(....);
}
(不是真的,因为泛型被删除了,但这是一个很好的思考方式。)
但是
TrafficReport
不是daytranfficreport
的子类型,因此您不能这样返回它。首先我有一个错误,更改后的返回类型是t
。我很抱歉。第二,我想让TrafficReportMapper
具有与目前相同的功能,但也能够扩展到其他类型。底线-我需要一个TrafficReportMapper
来返回TrafficReport
,但我希望它更一般我认为:DayTrafficReport=trm.mapRow(null,0)
将抛出ClassCastException
,而这不是你希望从一般类中得到的行为。@kajacx你完全正确。这将从我的答案中删除,因为它完全玷污了泛型。感谢您注意到首先我有一个错误,更改后的返回类型是T
。我很抱歉。第二,我想让TrafficReportMapper
具有与目前相同的功能,但也能够扩展到其他类型。底线-我需要一个TrafficReportMapper
来返回TrafficReport
,但我希望它更一般我认为:DayTrafficReport=trm.mapRow(null,0)
将抛出ClassCastException
,而这不是你希望从一般类中得到的行为。@kajacx你完全正确。这将从我的答案中删除,因为它完全玷污了泛型。感谢您注意到您无法返回TrafficReport
方法的对象希望您返回t
T
可以是TrafficReport
,但也可以是SomeTrafficReportSubclass
。您不能返回方法的TrafficReport
对象希望您返回T
T
可以是TrafficReport
,但也可以是somettrafficreportsubclass
。