Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/388.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将泛型类作为方法的泛型参数传递_Java_Spring_Generic Collections - Fatal编程技术网

Java 如何将泛型类作为方法的泛型参数传递

Java 如何将泛型类作为方法的泛型参数传递,java,spring,generic-collections,Java,Spring,Generic Collections,我在将类作为方法的泛型参数传递时遇到问题,例如,我有一个简单的方法: <T> T sendRequest(SomeRestApiRequest request, Class<T> responseClass) 对于如下所示的ItemListJSON.class: @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"totalSize","items"}) public class ItemLis

我在将类作为方法的泛型参数传递时遇到问题,例如,我有一个简单的方法:

<T> T sendRequest(SomeRestApiRequest request, Class<T> responseClass)
对于如下所示的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方法进行了调试,发现错误发生在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
    }
private T processResponse(响应响应,类responseClass)抛出ParseException,IOException{
ObjectMapper om=新的ObjectMapper();
enable(反序列化功能。接受\u单个\u值\u作为\u数组);
返回om.readValue(response.getBody(),responseClass);//抛出异常
}
使用

ParameteredTypeReference typeRef=新的ParameteredTypeReference(){};
查看从中截取的代码

RestTemplate RestTemplate=new RestTemplate();
ParameteredTypeReference listOfString=新的ParameteredTypeReference(){};
ResponseEntity response=restemplate.exchange(baseUrl,HttpMethod.GET,null,listOfString);
HttpHeaders=response.getHeaders();
MediaType contentType=headers.getContentType();
long date=headers.getDate();
List getOrDefault=headers.getOrDefault(“X-Forwarded”,Collections.singletonList(“不存在”);

通过传递
com.fasterxml.jackson.core.type.TypeReference
而不是
Class

公共类GenericSerializationTest{
@数据//龙目
公共静态类ItemListJSON{
私人清单项目;
}
@数据//龙目
公共静态类结构示例{
私有最终字符串名;
私人最终双倍价格;
}
公共静态类发送器{
私有最终ObjectMapper ObjectMapper=新ObjectMapper();
public T sendRequest(字符串json,类型引用TypeReference)引发IOException{
//发送方逻辑——在本例中,我假设json是API响应
返回objectMapper.readValue(json,typeReference);
}
}
@试验
public void testMethod()引发IOException{
发送方=新发送方();
ItemListJSON test=sender.sendRequest(“{\”items\”:[{\“name\”:\“MacBook Pro\”,\“price\”:101.345},{\“name\”:\“MacMini\”,\“price\”:102.345}),new TypeReference(){});
assertEquals(“应仅包含2项”,2,test.getItems().size());
assertEquals(“第一项的名称不正确”,“MacBook Pro”,test.getItems().get(0.getName());
assertEquals(“第二项的名称不正确”,“MacMini”,test.getItems().get(1.getName());
}
}

显示sendRequest(SomeRestApiRequest请求,类responseClass)的主体@isah我编辑了我的帖子,以显示异常抛出的位置。JSON响应作为字符串,
response.getBody()
(stringified)是什么?
@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...
}
ItemListJSON<SalonJSON> itemList = new ItemListJSON<SalonJSON>();
itemList = someRestClient.sendRequest(req, ItemListJSON.class);
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
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
    }
ParameterizedTypeReference<ItemListJSON<SalonJSON>> typeRef = new ParameterizedTypeReference<ItemListJSON<SalonJSON>>() {};
RestTemplate restTemplate = new RestTemplate();
ParameterizedTypeReference<List<String>> listOfString = new ParameterizedTypeReference<List<String>>() {};
ResponseEntity<List<String>> response= restTemplate.exchange(baseUrl,HttpMethod.GET,null, listOfString);
HttpHeaders headers = response.getHeaders();
MediaType contentType = headers.getContentType();
long date = headers.getDate();
List<String> getOrDefault = headers.getOrDefault("X-Forwarded", Collections.singletonList("Does not exists"));
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());
    }
}