【问题标题】:Returning a bounded wildcard返回有界通配符
【发布时间】:2015-04-23 05:20:54
【问题描述】:

我有一个接口,该接口带有一个返回有界通配符的方法:

public Collection<? extends CacheableObject> retrieveConnections(CacheableObject element);

这个接口是由一个类名PersistentAbstraction实现的,它返回一个CacheableObject

public Collection<? extends CacheableObject> retrieveConnections(CacheableObject element) {
    Collection<CacheableObject> connections = new HashSet<CacheableObject>();
    for(CacheableRelation relation : connectedElements) {
        if(relation.contains(element)) {
            connections.add(relation.getRelatedElement(element));
        }
    }
    return connections;
}

现在我有一个名为UserCacheableObject 实现和一个具有PersistentAbstraction 实例的类。我正在尝试执行以下操作:

public Collection<User> retrieveConnections(User user) {
    Collection<User> collection = (Collection<User>) persistentAbstraction.retrieveConnections(user);
    return collection;
}

但它说:

Type safety: Unchecked cast from Collection<capture#1-of ? extends CacheableObject> to Collection<User>

我不确定该警告背后的原因是什么。 User 不是 CacheableObject 吗?警告是什么意思?

【问题讨论】:

    标签: java generics return


    【解决方案1】:

    该错误基本上意味着您不能将Collection&lt;? extends CacheableObject&gt; 分配给Collection&lt;User&gt;,这是因为无法保证在运行时集合对象的类型为User

    Collection&lt;? extends CacheableObject&gt; 引用很可能指向包含 AnotherCacheableObject 类型项目的集合,其中 AnotherCacheableObject 实现 CacheableObject

    【讨论】:

      【解决方案2】:

      retrieveConnections 返回一个Collection&lt;? extends CacheableObject&gt;。这可能是Collection&lt;User&gt;,但编译器无法知道这一点,因为它可能是Collection&lt;OtherClass&gt;,其中OtherClass 是实现CacheableObject 的其他类。

      有几种方法可以解决此问题。一种方法是使retrieveConnections 成为带有签名的通用方法

      public <T extends CacheableObject> Collection<T> retrieveConnections(T element)
      

      (您需要相应地修改方法的主体)。然后persistentAbstraction.retrieveConnections(user) 将具有Collection&lt;User&gt; 类型,并且不需要演员表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-23
        • 1970-01-01
        相关资源
        最近更新 更多