【发布时间】:2014-12-23 12:48:18
【问题描述】:
我正在尝试在工厂类中创建一个方法。子类型的返回必须与声明的参数类型相同。
方法声明有效,但是当我尝试使用时,该方法没有返回预期的类型。
这里有一个类来说明我的问题:
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 从 ? 的捕获中扩展对象
有没有办法做这样的事情?
在此先感谢
【问题讨论】:
标签: java generics nested-generics