[英]Java static factory for classes that implement interface with generic method parameter
I have the following static factory implementation:我有以下 static 工厂实施:
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: FirstHandler 和 SecondHandler 都实现了以下接口:
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.请求 object 是两个附加类的基础 class,其中包含请求的附加数据。
In my main class, I'm trying to do the following:在我的主要 class 中,我正在尝试执行以下操作:
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.请求的来源是 HTTP 请求主体,它可以解析为任一请求子类。 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?我知道 Request object 不会自行扩展,这听起来很奇怪,但是有没有办法让我仍然可以这样调用 handle 方法?
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.