Java 有没有一种方式来表达“我的爱”呢;签署「;一个临时山脉的?
基于此,我决定实现我自己的Java 有没有一种方式来表达“我的爱”呢;签署「;一个临时山脉的?,java,datetime,java-time,Java,Datetime,Java Time,基于此,我决定实现我自己的MutableClock,用于工作原理稍有不同的单元测试目的: class MutableClock extends Clock { private final List<Instant> instants = new ArrayList<>(); public MutableClock(Instant now, TemporalAmount... amounts) { Objects.requireNonNull(now, "
MutableClock
,用于工作原理稍有不同的单元测试目的:
class MutableClock extends Clock {
private final List<Instant> instants = new ArrayList<>();
public MutableClock(Instant now, TemporalAmount... amounts) {
Objects.requireNonNull(now, "now must not be null");
Objects.requireNonNull(amounts, "amounts must not be null");
instants.add(now);
for (TemporalAmount amount : amounts) {
Instant latest = instants.get(instants.size() - 1);
instants.add(latest.plus(amount));
}
}
@Override
public Instant instant() {
Instant latest = instants.get(0);
if (instants.size() > 1) {
instants.remove(0);
}
return latest;
}
...
所以,基本上,我只能在时钟上“向前”打勾。当然,这在大多数情况下是有意义的,但由于所有这些都是为了单元测试,我可以想象我想要使用这样一个MutableClock
实例,并让它返回不总是“增加”的实例
但是当看界面时:没有办法表达一个否定的时间量?!换句话说:TemporalAmount
的实例似乎没有“签名”
那么,我们如何才能做到这一点呢?这个问题可以很直接地解决:只需查看该接口的具体实现,即。该类实际上提供了否定持续时间实例的功能 因此,当通过负持续时间时,上述实现已经起作用:
@Test
public void testNegativeAdjustments() {
Instant now = Instant.now();
Duration amount = Duration.ofSeconds(5);
TemporalAmount negativeAmount = amount.negated();
MutableClock underTest = new MutableClock(now, negativeAmount);
assertThat(underTest.instant(), is(now));
assertThat(underTest.instant(), is(amount.subtractFrom(now)));
}
TemporalAmount
由java.time中的两个类实现:Duration
和Period
。当然,用户也可以编写自己的接口实现。我没有检查,但是我假设ThreeTen额外项目的PeriodDuration
类也实现了接口。您可能认为不能将期间
添加到即时
中,因为即时
不知道天数、月份和年份,这是期间
的组成部分。总的来说,你确实不能,但有些情况下你可以。添加Period.ZERO
或Period.ofWeeks(3)
进展顺利(后者将一周定义为168小时,我们知道当夏季开始和结束时,这是不正确的,但这是可能的)。简而言之:我们不能安全地假设TemporalAmount
是持续时间
如果您想对接口编程,一个相当简单的技巧是在添加量时检查时钟是否实际倒转:
Instant latest = instants.get(instants.size() - 1);
Instant newInstant = latest.plus(amount);
if (newInstant.isBefore(latest)) {
// The amount was negative; do whatever handling of the situation you need
} else {
instants.add(newInstant);
}
当然,如果您想让时钟倒转,则不需要对这种情况进行特殊处理(您可以省略if
-else
构造)。正如您在自己的回答中所指出的,创建负数不会带来任何问题,例如持续时间秒(-5)
或周周期(-3)
为什么界面不提供负数测试和/或否定方法?
虽然持续时间
总是明确地为负、零或正,但这在期间
中并不成立<代码>月周期(1)。根据月份的选择,最小天数(30)
可能为负、零或正。奇怪的是,Period
有一个isNegative
方法,但它只是测试三个单位(年、月、日)中是否有一个是负数,所以语义不是您需要的。所以Period.ofMonths(1).minusDays(3).isNegative()
返回true
投票人的任何评论?“没有办法表达否定的时间?!”嗯?让get(临时单位)
返回一个负值。有趣的一点。也许真正的答案也是改变我的代码,不再使用那个接口,而是简单地依赖于持续时间本身。这清楚地表达了他们的意图,也避免了人们在某些情况下推搡,然后奇怪的事情发生。听起来不错。java.time的接口并不都是供日常应用程序(或测试)程序员使用的,因此,如果直接依赖Duration
使事情变得更简单或更容易,那么一定要这样做(我急忙向你自己的答案投了赞成票)。
Instant latest = instants.get(instants.size() - 1);
Instant newInstant = latest.plus(amount);
if (newInstant.isBefore(latest)) {
// The amount was negative; do whatever handling of the situation you need
} else {
instants.add(newInstant);
}