我正在尝试在工厂类中创建一个方法。子类型的返回必须与声明的参数类型相同。
方法声明有效,但是当我尝试使用时,该方法没有返回预期的类型。
这是一个说明我的问题的类:
import java.util.HashMap;
/**
*
* @author Marcos Martinewski Alves
*/
public class FooParserFactory {
private static final HashMap<Class<? extends Foo>, FooParser<? extends Foo>> fooParsers = new HashMap();
public static FooParser<? extends Foo> getFooParser(Class<? extends Foo> cls) {
initParsers();
FooParser<? extends Foo> parser = fooParsers.get(cls);
if (parser == null) {
throw new RuntimeException("FooParser not found for class "+cls);
}
return parser;
}
private static void initParsers() {
if (fooParsers.isEmpty()) {
// populate fooParsers hashmap
}
}
}
foo 接口
public interface Foo {
}
foo 实现
public class FooImpl implements Foo {
}
FooParser
public interface FooParser<T extends Foo> {
public T parse(Object object);
}
以及出现问题的地方
public class FooParserUsage {
public void useFooParser(Object source) {
FooImpl fooImpl = FooParserFactory.getFooParser(FooImpl.class).parse(source); // here
}
}
我正在使用 NetBeans IDE 8.1,但出现以下错误:
不兼容的类型:CAP#1 不能转换为 FooImpl,其中 CAP#1 是一个快速的类型变量 CAP#1 从捕获的 ?
有没有办法做这样的事情?
提前谢谢了