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

尼蒂卡

我现在有以下方法

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;
    }

但是对于每个不同的类,我都必须创建一个新方法以将响应转换为类

有没有什么办法可以通过为我要转换的类名添加一个参数来使它通用?

尼蒂卡

感谢@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;
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章