我想学习使用泛型的第一次,一个相当复杂的方式为返回类型最佳实践。我也使用Jackson 2进行反序列化。什么是使用Java泛型和工厂模式
我在我的return语句每次铸造。有人能告诉我这是错的吗?如果是这样,有什么更好的方法来做到这一点?
下面是一个简单的例子类,演示了这种情况:
class ResourceFactory <T extends Resource>{
List<T> getResources(String path)
{
ResourcesResponse rgRes = new ObjectMapper()
.readValue(response.body().byteStream(), ResourcesResponse.class)
return (List<T>)rgRes.resources
}
}
UPDATE:
每一个评论,这里是另一类机构是什么样的超简化的例子。
class ResourceResponse {
List<Resource> resources
}
class ResourceGeneric extends Resource {
}
class ResourceTypeOne extends Resource {
public String typeOneOnlyProperty
}
class ResourceTypeTwo extends Resource {
public String typeTwoOnlyProperty
}
您可以分享“ResourcesResponse”和“Resource”的定义吗? –
我已经添加了一些模拟。如果你想看杰克逊的注释,我也可以嘲笑这些,但是杰克逊的反序列化没有问题。我只是想确定在每个回报声明中投出(列表)是否最好。 –
solvingJ
'ResourceResponse'应该是'ResourceResponse'。资源应该是'List '。你应该传递一个TypeReference >作为参数。 –