我有一个问题,传递类作为方法的通用参数,例如。我有一个简单的方法:
<T> T sendRequest(SomeRestApiRequest request, Class<T> responseClass)
解析对指定表单的响应。我以这种方式使用它们:
ItemListJSON itemList = new ItemListJSON();
itemList = someRestClient.sendRequest(req, ItemListJSON.class);
对于ItemListJSON.class看起来像这样:
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"totalSize","items"})
public class ItemListJSON {
@JsonProperty("items")
private List<SalonJSON> items;
@JsonProperty("totalSize")
private int totalSize;
//...getters, setters...
}
一切都很好。但我的问题是:
是否可以将泛型类作为sendRequest方法的参数传递?
我希望ItemListJSON类是通用的,在我的例子中:
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"totalSize","items"})
public class ItemListJSON<T> {
@JsonProperty("items")
private List<T> items;
@JsonProperty("totalSize")
private int totalSize;
//...getters, setters...
}
但是当我尝试以这种方式使用sendRequest方法时:
ItemListJSON<SalonJSON> itemList = new ItemListJSON<SalonJSON>();
itemList = someRestClient.sendRequest(req, ItemListJSON.class);
我在Eclipse IDE上收到了警告
类型安全:ItemListJSON类型的表达式需要未经检查的转换以符合ItemListJSON
当调用方法时,我在服务器控制台中出错:
SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to xxx.ServiceCategoryJSON] with root cause
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to xxx.ServiceCategoryJSON
@编辑:
我重新编写了sendRequest方法,发现processResponse方法发生了错误,其中是ObjectMapper对对象的响应映射。
private <T> T processResponse(Response response, Class<T> responseClass) throws ParseException, IOException {
ObjectMapper om = new ObjectMapper();
om.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
return om.readValue(response.getBody(), responseClass); //throw exception
}
你可以通过传递com.fasterxml.jackson.core.type.TypeReference
而不是Class<T>
来做到这一点
public class GenericSerializationTest {
@Data //lombok
public static class ItemListJSON<T> {
private List<T> items;
}
@Data //lombok
public static class StructureExample {
private final String name;
private final Double price;
}
public static class Sender {
private final ObjectMapper objectMapper = new ObjectMapper();
public <T> T sendRequest(String json, TypeReference typeReference) throws IOException {
//sender logic - in this case I assume that json is API response
return objectMapper.readValue(json, typeReference);
}
}
@Test
public void testMethod() throws IOException {
Sender sender = new Sender();
ItemListJSON<StructureExample> test = sender.sendRequest("{\"items\": [{\"name\":\"MacBook Pro\",\"price\":101.345}, {\"name\":\"MacMini\",\"price\":102.345}]}", new TypeReference<ItemListJSON<StructureExample>>() {});
assertEquals("Should contain only 2 items", 2, test.getItems().size());
assertEquals("Name of first item is not correct", "MacBook Pro", test.getItems().get(0).getName());
assertEquals("Name of second item is not correct", "MacMini", test.getItems().get(1).getName());
}
}
使用
ParameterizedTypeReference<ItemListJSON<SalonJSON>> typeRef = new ParameterizedTypeReference<ItemListJSON<SalonJSON>>() {};
请参阅qazxsw poi的代码片段
the rest template intro