首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >第三方图书馆的通用方法限制规避

第三方图书馆的通用方法限制规避
EN

Stack Overflow用户
提问于 2015-10-30 10:23:07
回答 1查看 247关注 0票数 3

我使用cqengine引擎进行收集指数化:

代码语言:javascript
复制
Attribute<UtilizationEntry, LocalDate> startDateAttr = new SimpleAttribute<UtilizationEntry, LocalDate>() {
    @Override
    public LocalDate getValue(UtilizationEntry object, QueryOptions queryOptions) {
        return object.getStartDate();
    }
};
IndexedCollection<UtilizationEntry> entries = new ConcurrentIndexedCollection<>();
entries.addIndex(NavigableIndex.onAttribute(startDateAttr)); // compilation error in this line

没有编译此代码是因为:

代码语言:javascript
复制
Error:(61, 70) java: no suitable method found for onAttribute(com.googlecode.cqengine.attribute.Attribute<entities.UtilizationEntry,java.time.LocalDate>)
method com.googlecode.cqengine.index.navigable.NavigableIndex.<A,O>onAttribute(com.googlecode.cqengine.attribute.Attribute<O,A>) is not applicable
  (inferred type does not conform to equality constraint(s)
    inferred: java.time.chrono.ChronoLocalDate
    equality constraints(s): java.time.chrono.ChronoLocalDate,java.time.LocalDate)
method com.googlecode.cqengine.index.navigable.NavigableIndex.<A,O>onAttribute(com.googlecode.cqengine.index.support.Factory<java.util.concurrent.ConcurrentNavigableMap<A,com.googlecode.cqengine.resultset.stored.StoredResultSet<O>>>,com.googlecode.cqengine.index.support.Factory<com.googlecode.cqengine.resultset.stored.StoredResultSet<O>>,com.googlecode.cqengine.attribute.Attribute<O,A>) is not applicable
  (cannot infer type-variable(s) A,O
    (actual and formal argument lists differ in length))

可能是缺乏库设计:LocalDate实现了扩展Comparable<ChronoLocalDate>ChronoLocalDate,这意味着在泛型方法声明中必须使用通配符边界。我想,在本例中,创建实现Comparable<>LocalDate包装器是一个解决办法。

也许,这个问题还有其他的解决办法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-30 14:02:25

我认为,创建像包装器一样的新类,对于修复通用签名错误来说是相当大的开销。我会创建一个委托方法,比如

代码语言:javascript
复制
@SuppressWarnings("unchecked")
static <A extends Comparable<A>,O>
               NavigableIndex<A,O> onAttribute(Attribute<O,? extends A> attribute) {
    return NavigableIndex.onAttribute((Attribute)attribute);
}

实际上,问题在于声明A extends Comparable<A>,它应该是A extends Comparable<? super A>,但是在这里修复它不会有帮助,因为这个模式在整个API中传播,允许这样的返回类型只会在下一个API使用时引发错误。但是,据我所知,Attribute只生成A,而不使用它们,所以我们可以在这里放松签名,接受Attribute<…,? extends A>,遵循果胶模式。

有了这个助手,您的代码应该可以顺利编译:

代码语言:javascript
复制
IndexedCollection<UtilizationEntry> entries = new ConcurrentIndexedCollection<>();
entries.addIndex(onAttribute(startDateAttr));
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33433703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档