3 回答

TA贡献1887条经验 获得超5个赞
首先,让方法返回T而不是Object:
public static <T> T getForEntity(...)
然后,实现它以返回一个 T。readValue返回正确的类,因为您传入了Class<T>并且它的签名也等同于public <T> T readValue(..., Class<T> clazz),所以您可以这样做:
T obj = getResponseJsonMapper.readValue(getResponseJson, responseType);
return obj;

TA贡献1802条经验 获得超5个赞
您只需要传递一个Class<T>参数。
请注意,您不需要对readValue方法响应进行强制转换,因为您已经clazz作为参数传递,因此它返回一个clazz元素。
您的错误只是您将结果分配给了 Object 类型的对象。比退货了。删除不必要的赋值并直接从对 的调用结果中返回readValue。
public static <T> T getForEntity(String url, Class<T> clazz) throws InterruptedException,
ExecutionException, IOException {
Response getResponse = callWithHttpGet(url);
String getResponseJson = getResponse.getBody();
ObjectMapper getResponseJsonMapper = new ObjectMapper();
return getResponseJsonMapper.readValue(getResponseJson, clazz);
}

TA贡献1883条经验 获得超3个赞
使用 T 作为返回参数并进行强制转换(假设可以进行强制转换 - 否则会出现运行时异常)。
public static <T> T getForEntity(String url, Class<T> responseType) throws InterruptedException, ExecutionException, IOException{
Response getResponse = callWithHttpGet(url);
String getResponseJson = getResponse.getBody();
ObjectMapper getResponseJsonMapper = new ObjectMapper();
T obj = (T)getResponseJsonMapper.readValue(getResponseJson, responseType);
return obj;
}
而且在特定情况下,您甚至可以跳过演员表(如果 ObjectMapper 已经返回正确的类型 - 例如杰克逊)。
添加回答
举报