Java泛型作为参数

时间:2013-01-10 22:28:46

标签: c# java generics

所以我有一堆基本上可以进行相同调用的方法,唯一的区别是泛型的类名。例如:

电流:

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中正确地做到这一点。

编辑:为清楚起见。

2 个答案:

答案 0 :(得分: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,因为Java中不可能使用new S()之类的东西:

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

这样的东西
MyClass.<ARequest, AResponse>serviceCall(request, new AResponse(), delegate)
这里没有必要

因为编译器会为你推断出类型参数。

答案 1 :(得分: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)一样调用它。