【发布时间】:2017-09-04 18:56:04
【问题描述】:
我有一个包含要发送到 UI 的响应的类。蓝图如下:
class Response<T extends CustomObject> {
private String var1;
private String var2;
private List<T> custom; (eg. customOne, customTwo)
}
我可以拥有不同的对象,例如扩展 CustomObject 的自定义对象,并且基于该 Response 类将具有不同的 customObject 列表。
应用服务逻辑后,我得到一个原始响应,并根据我尝试以不同方式解析的自定义对象。
CusomOne 和 CustomTwo 将具有不同的结构:
class CustomOne extends CustomObject {
private String v1;
}
class CustomTwo extends CustomObject {
private String v2;
}
我有一个抽象解析函数,它将根据所选择的对象被调用。函数定义为:
public abstract ResponsePayLoad<? extends CustomObject> parseResponse(String response);
ReponsePayLoad 是另一个具有其他字段的类,包括 CustomObject。 ResponsePayLoad 类的蓝图如下:
class ResponsePayLoad<T extends CustomObject> {
private String varX;
private List<T> value;
}
两个 customObjects 的解析函数如下:
public ResponsePayLoad<customOne> parseResponse(String response){
CustomOne one = ; // parsingLogic
return one;
}
public ResponsePayLoad<customTwo> parseResponse(String response){
CustomTwo two = ; // parsingLogic
return two;
}
在我编写代码时的服务逻辑中:
ResponsePayLoad<CustomObject> responseObj = parseResponse(response);
我需要将它类型转换为我不想要的 ResponsePayLoad。
谁能告诉我如何跳过使用“?”在抽象功能中仍然保持相同的逻辑?此外,我不想像上面定义的那样进行类型转换。任何帮助将不胜感激。
【问题讨论】:
标签: java generics architecture generic-programming