我有这样的方法:
private static <T extends HomerMessage> HomerMessage postRequest(String path, HomerMessage json) throws IOException, HomerDoh
{
RequestBody body = RequestBody.create(JSON, toJson(json));
Request request = new Request.Builder().url("http://" + path).post(body).build();
String response = new OkHttpClient().newCall(request).execute().body().string();
System.out.println(response);
JsonNode responseNode = new ObjectMapper().readValue(response, JsonNode.class);
if(!"200".equals(responseNode.get("status")))
{
throw readData(response, new TypeReference<HomerDoh>() {});
}
return readData(response, new TypeReference<T>() {});
}
private static <T> T readData(String is, TypeReference<T> ref) throws IOException
{
return mapper.readValue(is, ref);
}
一切正常,但我不知道如何调用它...... 我尝试过:
AuthResponse ar = HomerClient.postRequest(url + "/api/v1/session", auth);
最后一个表达式无法编译。
如何在Java中调用参数化方法?
AuthResponse 扩展了 HomerMessage
最佳答案
您的代码无法编译,因为它没有返回 AuthResponse
:它返回 HomerMessage
。
如果将方法的返回类型更改为:
,则可以将返回类型设置为AuthResponse
private static <T extends HomerMessage> T postRequest(
String path, HomerMessage json, TypeReference<T> typeRef)
throws IOException, HomerDoh
这是唯一正常完成的代码路径的返回类型。
正如 @SLaks 所指出的,您不能将 TypeReference
与泛型一起使用:
new TypeReference<T>() {}
由于删除,这在运行时相当于:
new TypeReference<Object>() {}
这几乎肯定不是您想要的 - 否则您可以直接使用它,而不会在调用泛型方法时遇到问题。
您需要实际传入具体的 TypeReference
作为参数:
private static <T extends HomerMessage> T postRequest(
String path, HomerMessage json, TypeReference<T> typeRef)
throws IOException, HomerDoh
那么你可以简单地称之为:
AuthResponse response = postRequest(
url + "/api/v1/session", auth,
new TypeReference<AuthResponse>() {});
并且类型T
是从第三个参数推断出来的。
关于java - Java中如何调用参数化方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36772406/