如何在Java中调用参数化方法?
我有这样一个方法:如何在Java中调用参数化方法?,java,generics,Java,Generics,我有这样一个方法: 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()
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);
}
最后一个表达式不编译
如何在Java中调用参数化方法
AuthResponse扩展HomerMessage您需要提供类的名称,其中定义了
静态方法:
Exception ar = SomeClass.<Exception>getException();
Exception ar=SomeClass.getException();
表达式Exception ar=getException()代码>无法编译,因为泛型方法参数化习惯用法在参数化之前需要一个类名(如果方法不是静态的,则需要变量名)
例如:
Exception ar = MyClass.<Exception>getException();
Exception ar=MyClass.getException();
例如,方法:
Exception ar=theObject.getException()代码>
Exception ar=this.getException()代码>
您的代码没有编译,因为它没有返回AuthResponse
:它正在返回HomerMessage
如果将方法的返回类型更改为:
private static <T extends HomerMessage> T postRequest(
String path, HomerMessage json, TypeReference<T> typeRef)
throws IOException, HomerDoh
由于擦除,这在运行时相当于:
new TypeReference<Object>() {}
那么您可以简单地称之为:
AuthResponse response = postRequest(
url + "/api/v1/session", auth,
new TypeReference<AuthResponse>() {});
AuthResponse-response=postRequest(
url+“/api/v1/session”,认证,
新类型引用(){});
类型T
是从第三个参数推断出来的。你得到了什么错误?顺便说一句,这个方法完全被破坏了;它需要使用TypeReference
作为参数。在postRequest
方法的throws
子句中,还应该将HomerDoh
替换为T
,并在调用throw readData(response,typeRef)
时使用typeRef
。否则,您的代码将无法编译。@RZet您确定吗?看起来还可以。非常确定您将得到'Unhandled exception type T'
编译错误。这是方法返回的类型readData()
。@RZet否。试试看。返回类型和抛出类型是非常独立的。这是我在创建的示例代码中得到的。你是否真的自己编写了代码,或是背下来了?
new TypeReference<Object>() {}
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>() {});