我正在尝试在工厂类中创建一个方法。子类型的返回值必须与声明的参数类型相同。
方法声明有效,但是当我尝试使用时,该方法没有返回预期的类型。
这是一个说明我的问题的类(class):
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 接口(interface)
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 是一个 frash 类型变量 CAP#1 从捕获中扩展对象?
有没有办法做这样的事情?
提前非常感谢
最佳答案
只是因为<? extends Foo>
看起来与 <? extends Foo>
相同并不意味着它们兼容:-)
您可以尝试按如下方式重新表述:
public static <T extends Foo> FooParser<T> getFooParser(Class<T> cls) {
// ^^^^^^^^^^^^^^^ ^ ^
// introduce a type now these two are "compatible"
// variable
initParsers();
// This line will however require a cast. Judge for yourself if it is safe.
FooParser<T> parser = (FooParser<T>) fooParsers.get(cls);
if (parser == null) {
throw new RuntimeException("FooParser not found for class " + cls);
}
return parser;
}
关于java - 声明从声明类型返回泛型子类型的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27620715/