So I have a bunch of methods that essentially make the same call the only difference is class names of generics. Example:
Current:
public void methodA(ARequest request, ADelegate delegate)
{
JsonClient<ARequest, AResponse> client = new JsonClient<ARequest, AResponse>(request.ServiceServerUrl, request, new AResponse());
client.sendRequest(delegate);
}
public void methodB(BRequest request, BDelegate delegate)
{
JsonClient<BRequest, BResponse> client = new JsonClient<BRequest, BResponse>(request.ServiceServerUrl, request, new BResponse());
client.sendRequest(delegate);
}
What I want to do is:
private void serviceCall<R extends RequestBase, S extends ResponseBase>(ADelegate delegate)
{
JsonClient<R, S> client = new JsonClient<R, S>(request.ServiceServerUrl, request, new AResponse());
client.sendRequest(delegate);
}
public void methodA(ARequest request, ADelegate delegate)
{
serviceCall<ARequest, AResponse>(delegate);
}
public void methodB(BRequest request, BDelegate delegate)
{
serviceCall<BRequest, BResponse>(delegate);
}
I think this is possible in C# but I just want to know how to properly do this in Java.
Edit: For clarity.
You should be able to write the following:
private <R extends RequestBase, S extends ResponseBase> void serviceCall(
R request,
S response,
ADelegate delegate
) {
JsonClient<R, S> client = new JsonClient<R, S>(request.ServiceServerUrl, request, response);
client.sendRequest(delegate);
}
Note that the caller must instantiate and pass in response
, since something like new S()
isn't possible in Java:
public void method(ARequest request, ADelegate delegate) {
serviceCall(request, new AResponse(), delegate);
}
Something like
MyClass.<ARequest, AResponse>serviceCall(request, new AResponse(), delegate)
isn't necessary here because the compiler infers the type arguments for you.
Do you mean?
public <T extends RequestBase, E extends ResponseBase> void method(T request, E delegate)
{
JsonClient<T, E> client = new JsonClient<T, E>(request.ServiceServerUrl, request, new AResponse());
client.sendRequest(delegate);
}
and invoke it like ClassName.<ARequest, AResponse>method(request, response)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.