Java中的程序如何在不重新编译程序的情况下更新Date对象?

How does the Date object update without recompiling the program in Java?

示例:

System.out.println(new Date());

现在显然这是一个更大程序的一部分,但您可以看到它的作用。现在,我 运行 编译一次,然后 运行 程序。然后,无需再次编译程序,我 运行 它和日期更新。这可能看起来很愚蠢,但是如何在不更新字节码的情况下更新日期?

根据我阅读的理解,Java 编译器获取我的源代码并将其编译为字节码,保存在 class 文件中。 JIT 将此代码转换为机器代码,然后 运行s。但是,Date 对象的状态不会保持不变吗?显然不是。我只是对它的变化感到困惑。

使用无参数构造函数初始化的 Date 对象将访问 System.currTimeMilis() 并使用机器的当前时间戳。换句话说,时间戳不是 "compiled into it",而是包含访问机器时钟的代码,并在每次程序 运行.

时从那里获取时间戳

编译时间与 运行 时间

is correct. Objects defined in your code are constructed at run-time, not compile-time

Compilation 就像让工程师审查建筑师的建筑计划,然后写出更详细的规范。尚未建造建筑物。我们现在已经完全 准备好 建造,但直到“运行 时间”施工人员到达现场后才真正建造任何东西。

在这个比喻中,您的 source code is the architect’s drawings. The engineer’s more detailed specifications is the bytecode emitted by the Java compiler. The JVM 运行 应用程序的字节码是施工人员去现场工作。

另一种思考方式:

  • 类 在编译时确定。
  • 对象(实例)在 运行 时确定。

java.time

另外,你不应该使用 Date class。 class 和来自 Java 最早版本的其他遗留日期时间 classes 是 糟糕的 ,充满了糟糕的设计选择。多年前,现代的 java.time classes 取代了它们。

java.timeclass使用factory methods for instantiating rather than constructorsnew

Instant.now()  // Capture current moment in UTC. 
OffsetDateTime.now( ZoneOffset.UTC )  // Capture current moment in UTC. 
ZonedDateTime.now( ZoneId.of( "Africa/Casablanca" ) )  // Capture current moment as seen though the wall-clock time used by the people of a particular region (a time zone). 
LocalDate.of( 2018 , Month.JANUARY , 23 )  // A date-only value, without time-of-day and without time zone.