如何创建 return 泛型类型的泛型方法
How to create generic method to return generic type
我现在有以下方法
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;
}
但是对于每个不同的 class,我必须创建一个新方法来将响应转换为 class
有什么方法可以通过为我要转换的 class 名称添加一个参数来使其通用?
感谢@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 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;
}
但是对于每个不同的 class,我必须创建一个新方法来将响应转换为 class
有什么方法可以通过为我要转换的 class 名称添加一个参数来使其通用?
感谢@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;
}