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

Jar*_* K. 5 java spring generic-collections

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

<T> T sendRequest(SomeRestApiRequest request, Class<T> responseClass)
Run Code Online (Sandbox Code Playgroud)

它解析指定形式的响应。我以这种方式使用它们:

ItemListJSON itemList = new ItemListJSON();
itemList = someRestClient.sendRequest(req, ItemListJSON.class);
Run Code Online (Sandbox Code Playgroud)

对于 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...
}
Run Code Online (Sandbox Code Playgroud)

一切都很好。但我的问题是:

是否可以将泛型类作为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...
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试以这种方式使用sendRequest方法时:

ItemListJSON<SalonJSON> itemList = new ItemListJSON<SalonJSON>();
itemList = someRestClient.sendRequest(req, ItemListJSON.class);
Run Code Online (Sandbox Code Playgroud)

我在 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
Run Code Online (Sandbox Code Playgroud)

@编辑:

我调试了我的 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
    }
Run Code Online (Sandbox Code Playgroud)

luw*_*zek 2

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());
    }
}
Run Code Online (Sandbox Code Playgroud)