java - Clock.withZone 有什么意义?

标签 java

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/

相关文章:

java - 使用 Sockets 在客户端和服务器之间传输 HashMap (JAVA)

java - 从动态 Firebase 数据库中提取变量

java - 转换 Spring Data JPA 页面内容的类型

java - 当我尝试创建 Opengl ES 环境时,我的应用程序不断崩溃

Java 到 JSP - 如何将 Java 应用程序集成到 JSP 网页中?

java - 如何修复 'MediaPlayrer mp = new Mediaplayer.create(this, R.raw.filename.mpr) ' 因为创建时出现红色错误

java - Hibernate @ElementCollection - 需要更好的解决方案

java - 构建 WebService 应用程序的推荐方法是什么?

java - 为什么没有将操作结果放在并发 HashMap 上? putIfAbsent 的用例是什么?

java - 使用 ORM Lite 在数据库中存储自定义对象的数组列表