[英]I don't know why I'm getting an error simply by creating a new Clock object
I am getting an error that says "Cannot instantiate the type Clock" and I do not know why.我收到一条错误消息,指出“无法实例化时钟类型”,但我不知道为什么。
import java.time.Clock;
public class TS1 {
public long getTime(){
Clock c = new **Clock**(); //Error occurs here for bold Clock
return c.millis();
}
}
Quoting the javadoc of class Clock (added in java 8):引用 类时钟的javadoc (在java 8中添加):
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.这可以简化测试。
To use the millis()
method of the abstract Clock
class , you don't have to extend it, you can use given implementations in java.time package.要使用抽象Clock
类的millis()
方法,您不必扩展它,您可以使用java.time 包中的给定实现。 For example, you can declare the following method:例如,您可以声明以下方法:
import java.time.Clock;
public class App {
public static long getMillis(Clock clock){
return clock.millis();
}
}
In your you app you can get a system clock implementation, rather using a direct and static calling to System.currentTimeInMillis()
:在您的应用程序中,您可以获得系统时钟实现,而不是使用对System.currentTimeInMillis()
的直接和静态调用:
Clock systemClock = Clock.systemUTC();
System.out.println(getMillis(systemClock));
This app code depends on the operating system clock and it result varies between each running time.此应用程序代码取决于操作系统时钟,其结果因每次运行时间而异。
In your test code, you can use a fixed clock instance, so the results are deterministic and predictable, regardless of the testing time (Certainly, for many testing scenarios you would use a mock object):在您的测试代码中,您可以使用固定时钟实例,因此无论测试时间如何,结果都是确定性和可预测的(当然,对于许多测试场景,您将使用模拟对象):
import static org.junit.Assert.*;
import org.junit.Test;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
@Test public void checkSampleUTCTime(){
Clock fixedClock = Clock.fixed(Instant.parse("2016-04-21T11:54:20.00Z"), ZoneOffset.UTC);
assertEquals(1461239660000L,App.getMillis(fixedClock));
}
Also, some would say that joda time DateTimeUtils
class ( see javadoc ) is nicer option - since you can use setCurrentMillisFixed()
and setCurrentMillisSystem()
to alternate the system clock behavior, instead of java.time.Clock
dependency injection.此外,有些人会说 joda time DateTimeUtils
类( 请参阅 javadoc )是更好的选择 - 因为您可以使用setCurrentMillisFixed()
和setCurrentMillisSystem()
来替代系统时钟行为,而不是java.time.Clock
依赖注入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.