【问题标题】:Why Apache Commons Range#between doesn't work as expected with ZonedDateTime?为什么 Apache Commons Range#between 不能像预期的那样与 ZonedDateTime 一起工作?
【发布时间】:2023-02-19 15:12:46
【问题描述】:

我希望第一个是正确的。

作为ZonedDateTime implements ChronoZonedDateTime<LocalDate>,我尝试使用后者作为类型参数。我想这由于类型擦除而不起作用,但我不确定。

但只有第三个范围被正确编译。 你能解释一下为什么吗?

import org.apache.commons.lang3.Range;

import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.time.chrono.ChronoZonedDateTime;

public class Test {

    public static void main(String[] args) {
        
        Range<ZonedDateTime> range1 = Range.between(ZonedDateTime.now(), ZonedDateTime.now());
        Range<ChronoZonedDateTime<LocalDate>> range2 = Range.between(ZonedDateTime.now(), ZonedDateTime.now());
        Range<ChronoZonedDateTime<?>> range3 = Range.between(ZonedDateTime.now(), ZonedDateTime.now());
    }
}

【问题讨论】:

    标签: java generics apache-commons


    【解决方案1】:

    Range.between(T fromInclusive, T toInclusive) 返回一个 Range&lt;T&gt; 对象,其中 T 必须扩展 Comparable&lt;T&gt;。我们可以从JavaDoc看到这一点。

    你想为你的 T 使用 ZonedDateTime 对象。查看that JavaDoc,我们看到它实现了Comparable&lt;ChronoZonedDateTime&lt;?&gt;&gt;

    这就是为什么您必须使用 Range&lt;ChronoZonedDateTime&lt;?&gt;&gt; 作为返回值的类型。

    导致前两个示例出现编译错误的不是类型擦除。只是需要遵循您正在使用的对象的 API。前两个示例不满足提供实现 Comparable 的正确通用对象的要求。


    另一种观点:

    来自原始between(T fromInclusive, T toInclusive)T 的值需要是naturally comparable,就像这个更简单的相同通用方法示例中的值一样:

    Range<Integer> range = Range.between(1, 9);
    

    ...其中 Java Integer 类实现了 Comparable&lt;Integer&gt;


    您可以使用自然无法比较的对象,但是您必须provide your own comparator

    public static <T> Range<T> between(T fromInclusive, T toInclusive, Comparator<T> comparator)
    

    ...并且您的比较器必须提供比较规则。

    【讨论】:

      【解决方案2】:

      您可以使用:

      Range.between(ZonedDateTime.now(), ZonedDateTime.now(), ChronoZonedDateTime::compareTo)

      这将允许您使用 Range&lt;ZonedDateTime&gt;Range&lt;ChronoZonedDateTime&lt;LocalDate&gt;&gt; 作为返回类型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-09
        • 2015-09-16
        • 2015-10-12
        • 1970-01-01
        • 2021-09-07
        • 2014-10-14
        • 1970-01-01
        相关资源
        最近更新 更多