1

所以我有一堆方法,它们本质上是相同的调用,唯一的区别是泛型的类名。例子:

当前的:

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);
}

我想做的是:

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);
}

我认为这在 C# 中是可能的,但我只想知道如何在 Java 中正确地做到这一点。

编辑:为清楚起见。

4

2 回答 2

2

您应该能够编写以下内容:

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);
}

请注意,调用者必须实例化并传入response,因为new S()在 Java 中是不可能的:

public void method(ARequest request, ADelegate delegate) {
    serviceCall(request, new AResponse(), delegate);
}

就像是

MyClass.<ARequest, AResponse>serviceCall(request, new AResponse(), delegate)

这里不需要,因为编译器会为您推断类型参数。

于 2013-01-10T22:35:26.740 回答
1

你的意思是?

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);
}

并像ClassName.<ARequest, AResponse>method(request, response).

于 2013-01-10T22:31:05.783 回答