我不知道为什么我只是通过创建一个新的Clock对象来获得错误

时间:2016-04-16 20:54:13

标签: java time clock

我收到一条错误消息“无法实例化类型时钟”,我不知道为什么。

import java.time.Clock;
public class TS1 {

    public long getTime(){
        Clock c = new **Clock**(); //Error occurs here for bold Clock
        return c.millis();
    }   
}

1 个答案:

答案 0 :(得分:0)

Quoting the javadoc of class Clock (added in 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. 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():

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.