gpt4 book ai didi

java - Clock.withZone 有什么意义?

转载 作者:行者123 更新时间:2023-11-29 08:22:15 26 4
gpt4 key购买 nike

java.time.Clock 提供对 millisinstant 的访问,但无法访问任何依赖时区的内容。然而它包含一个时区并且需要一个用于构建。它似乎只用于 equals/hashcode。

static final class SystemClock extends Clock implements Serializable {
private static final long serialVersionUID = 6740630888130243051L;
private final ZoneId zone;

SystemClock(ZoneId zone) {
this.zone = zone;
}
@Override
public ZoneId getZone() {
return zone;
}
@Override
public Clock withZone(ZoneId zone) {
if (zone.equals(this.zone)) { // intentional NPE
return this;
}
return new SystemClock(zone);
}
@Override
public long millis() {
return System.currentTimeMillis();
}
@Override
public Instant instant() {
return Instant.ofEpochMilli(millis());
}
@Override
public boolean equals(Object obj) {
if (obj instanceof SystemClock) {
return zone.equals(((SystemClock) obj).zone);
}
return false;
}
@Override
public int hashCode() {
return zone.hashCode() + 1;
}
@Override
public String toString() {
return "SystemClock[" + zone + "]";
}
}

是否有理由在此类中包含 ZoneId

最佳答案

docs将 Clock 的全部目的描述为基本上是一对(毫秒生成器、时区),尤其是用于测试:

Instances of this class are used to find the current instant, which can be interpreted using the stored time-zone to find the current date and time. As such, a clock can be used instead of System.currentTimeMillis() and TimeZone.getDefault().

Use of a Clock is optional. All key date-time classes also have a now() factory method that uses the system clock in the default time zone. The primary purpose of this abstraction is to allow alternate clocks to be plugged in as and when required. Applications use an object to obtain the current time rather than a static method. This can simplify testing.

(强调)

例如,如果您想测试您的类在特定时区的特定时刻的行为,您可以注入(inject)一个 Clock.fixed 实例。在生产代码中,您将使用 Clock.system* 工厂之一。

关于java - Clock.withZone 有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com