'Java static factory for classes that implement interface with generic method parameter

I have the following static factory implementation:

public class HandlersFactory {
private static Map<ProviderType, Handler<? extends Request>> handlers;

public static Handler<? extends Request> get(ProviderType type) {
    if (handlers == null) {
        initializeHandlers();
    }

    if (handlers.containsKey(type)) {
        return handlers.get(type);
    }

    throw new HandlerNotFoundException("Handler " + type.toString() + " not found");
}

private static void initializeHandlers() {
    handlers = new HashMap<>();

    handlers.put(ProviderType.FIRST, new FirstHandler());
    handlers.put(ProviderType.SECOND, new SecondHandler());
}

FirstHandler and SecondHandler both implement the following interface:

public interface Handler<R extends Request> {
    void handle(R request);
}

The Request object is a base class of two additional classes that contains additional data of the request.

In my main class, I'm trying to do the following:

public void handle(Request request) {
    HandlersFactory.get(request.getProvider()).handle(request);
}

The source of the request is by an HTTP request body, and it can parse to either one of the request sub-classes. I'm getting the compile error saying: "Required type: capture of ? extends Request, provided Request".

I know that the Request object doesn't extend itself, it sounds weird, but is there a way I can still call the handle method this way?



Solution 1:[1]

Although not very elegant, the following modifications should work :

public static <T extends Request> Handler<T> get(ProviderType type) {

and

return (Handler<T>) handlers.get(type);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Seb34