类中的嵌套通用多态返回类型
我有一个类将包含要发送到UI的响应。蓝图是:类中的嵌套通用多态返回类型
class Response<T extends CustomObject> {
private String var1;
private String var2;
private List<T> custom; (eg. customOne, customTwo)
}
我能有这样的正在扩大CustomObject并根据该响应类将有不同的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。
任何人都可以告诉我如何跳过使用“?”在抽象函数中仍然保持相同的逻辑?此外,我不想像上面定义的那样类型化。任何帮助,将不胜感激。
如果我正确地理解了您,则返回类型parseResponse
分别为ResponsePayLoad<CustomOne>
和ResponsePayLoad<CustomTwo>
。
然后,它无法将结果存储在
ResponsePayLoad<CustomObject> responseObj = parseResponse(response);
由于不能向下转换的结果。在一个通用的方式,你会使用
ResponsePayLoad<? extends CustomObject> responseObj = parseResponse(response);
但同样你存储CustomOne
和CustomTwo
对象作为CustomObject
这意味着你失去类型的信息。然后演员是必要的。
你需要投
ResponsePayLoad<CustomObject> responseObj = parseResponse(response);
因为parseResponse
方法返回未知类型(ResponsePayLoad<? extends CustomObject>
)的ResponsePayload原因。
这里所能理解的是,未知类型可以是CustomObject
的子类型。它可以是CustomObject
本身(如你的情况)或其一些子类(CustomOne
,CustomTwo
等),但它不需要从字面上延伸CustomObject
。
因此,将完整响应转换为ResponsePayload
进一步使其具有通用性,尽管编译器必须在未经检查的情况下警告编译器。
The doc around generics wildcards用更好的例子解释了这一点。
...我怎么可以跳过使用 “?”在抽象函数中仍然保持相同的逻辑?
的另一种方法,以避免显式类型转换是被声明为您parseResponse
方法返回ResponsePayload
:
public abstract ResponsePayLoad parseResponse(String response);