简体   繁体   中英

How to use generics of generics in java interfaces

I am trying to write a generic interface for my base service. Here is what I tried at all:

Assume that we have a request and response object. Each request type must be bound to a response type, so we can handle response types of requests.

abstract class Response {

}    

abstract class Request<R extends Response> {

}

Now let's write some implementations about them:

class DummyResponse extends Response {

}

class DummyRequest extends Request<DummyResponse> {

}

Okay, we have implementations. Let's dive into the interface, where I struggled:

interface MyService {

   <R extends Response, T extends Request<R>> R getResponse(T request);

}

When I implement this MyService, I've got errors:

class MyServiceImpl implements MyService {

    //these method gives me error
    @Override
    public DummyResponse getResponse(DummyRequest request) {
        //do sth
        return response;
    }

}

So why am I doing this? Because I want to write lots of service implementations with their own request and response objects, so I can handle them from one point -- the service interface.

How can I do this with using interfaces? Or is it a wrong approach? What is the true way to do this?

Thanks in advance.

To implement the MyService interface correctly, you must provide a generic method getResponse that matches the type parameters. However, you are implicitly placing type arguments DummyResponse and DummyRequest , and you aren't declaring type parameters R and T as MyService 's getResponse method does.

The solution here is to move the type parameters R and T to the interface itself.

interface MyService<R extends Response, T extends Request<R>> {
    R getResponse(T request);
}

Then MyServiceImpl can supply type arguments to MyService when implementing it, and getResponse can use those type arguments to successfully implement the getResponse method.

class MyServiceImpl implements MyService<DummyResponse, DummyRequest> {

    // This now implements MyService correctly. 
    @Override
    public DummyResponse getResponse(DummyRequest request) {
        //do sth
        return 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.

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