简体   繁体   中英

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):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM