1

我正在尝试在工厂类中创建一个方法。子类型的返回必须与声明的参数类型相同。

方法声明有效,但是当我尝试使用时,该方法没有返回预期的类型。

这是一个说明我的问题的类:

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 从捕获的 ?

有没有办法做这样的事情?

提前谢谢了

4

1 回答 1

2

仅仅因为<? 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;
}
于 2014-12-23T12:52:45.127 回答