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?
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);
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.