【问题标题】:Declaring method returning generic subtype from a declaring type声明方法从声明类型返回泛型子类型
【发布时间】: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


    【解决方案1】:

    仅仅因为&lt;? extends Foo&gt; 看起来与&lt;? extends Foo&gt; 相同并不意味着它们是兼容的:-)

    您可以尝试将其重新表述如下:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-14
      • 2018-12-14
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多