简体   繁体   English

Java泛型作为参数

[英]Java Generics as parameters

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. 我认为这在C#中是可行的,但我只是想知道如何在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: 请注意,调用者必须实例化并传递response ,因为Java中不可能使用new S()

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) . 并像ClassName.<ARequest, AResponse>method(request, response)一样调用它ClassName.<ARequest, AResponse>method(request, response)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM