java—如何创建泛型方法以返回泛型类型

ercv8c1e  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(261)

我现在有以下方法

private classResponse getClassResponse(final Response response) {
        try {
            return mapper.readValue(mapper.writeValueAsString(response.getEntity()), classResponse.class);
        } catch (IOException e) {
            log.error("Error while mapping object: {} to classResponse with cause", response.getEntity(), e);
        }
        return null;
    }

但是对于每一个不同的类,我必须创建一个新的方法来将响应转换为类
是否有任何方法可以使它成为泛型的,通过为类名增加一个参数来转换?

plupiseo

plupiseo1#

谢谢@dbl的帮助。总结下面的答案,

private <T> T getResponse(final Response response, final Class<T> className) {
        try {
            return mapper.readValue(mapper.writeValueAsString(response.getEntity()), className);
        } catch (IOException e) {
            log.error("Error while mapping object: {} to class with cause", response.getEntity(), e);
        }
        return null;
    }

相关问题