Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
13.3k views
in Technique[技术] by (71.8m points)

Java抽象类中的泛型问题

抽象类代码如下:

public abstract class AbstractRankDataService {
 
 public JsonObject process(JsonObject obj) {
 List list = getRankModel(obj);
 fill(list); // 错误就在这里 A
 return new JsonObject();
 }
 
 public abstract List fill(List list);
 
 public List getRankModel(JsonObject jsonObject){
 // 此处省略具体实现
 return null;
 }
} 

实现类代码如下:

public class ARankDataService extends AbstractRankDataService {
 @Override
 public List fill(List rankModels) {
 // 此处处理rankModels报错,因为此时rankModels的类型是父类---BaseRankDataModel,提示类型转换异常
 }
}

具体描述:
在抽象类的抽象方法入参是List,但是在子类中List的内部对象是父类,报类型转换异常(父类转子类异常),求大神指点


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

这个和泛型没啥关系。
如果在fill中仅处理BaseRankDataModel。
按以下修正即可:

- public abstract List fill(List list);
+ public abstract List fill(List<BaseRankDataModel> list);

如果返回值List中的内容也是BaseRankDataModel,则还可以修正为:

+ public abstract List<BaseRankDataModel> fill(List<BaseRankDataModel> list);

然后在ARankDataService在实现抽像方法即可。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...