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

Java 如何创建泛型方法以返回泛型类型,java,generics,jackson,Java,Generics,Jackson,我现在有下面的方法 private classResponse getClassResponse(final Response response) { try { return mapper.readValue(mapper.writeValueAsString(response.getEntity()), classResponse.class); } catch (IOException e) { log.err

我现在有下面的方法

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;
    }
private T getResponse(最终响应,最终类名){
试一试{
返回mapper.readValue(mapper.writeValueAsString(response.getEntity()),className);
}捕获(IOE异常){
error(“将对象:{}映射到具有原因的类时出错”,response.getEntity(),e);
}
返回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;
    }
private T getResponse(最终响应,最终类名){
试一试{
返回mapper.readValue(mapper.writeValueAsString(response.getEntity()),className);
}捕获(IOE异常){
error(“将对象:{}映射到具有原因的类时出错”,response.getEntity(),e);
}
返回null;
}

编写一个泛型方法,使用
类作为参数。
@SuppresWarnings(“unchecked”)private T getResponse(final Response Response,class tClass){…return(T);}
@AnatolyG readValue在运行时需要该类来知道它创建的实例应该是什么类。关于编写泛型方法,您有什么问题吗?@tgdavies那么dbl的代码片段应该可以工作。但是,从我的观点来看,像这样的API说,放置任何类型,您将得到这种类型的结果/我可以处理任何类型,但这似乎不是真的。我更希望有许多方法,它们的签名中定义了特定/封闭的支持类型集。编写一个泛型方法,将
类作为参数。
@SuppresWarnings(“unchecked”)private T getResponse(final Response Response,class tClass){…return(T);}
@AnatolyG readValue在运行时需要该类来知道它创建的实例应该是什么类。关于编写泛型方法,您有什么问题吗?@tgdavies那么dbl的代码片段应该可以工作。但是,从我的观点来看,像这样的API说,放置任何类型,您将得到这种类型的结果/我可以处理任何类型,但这似乎不是真的。我更希望有许多方法,它们的签名中定义了特定/封闭的支持类型集