了解TimeUnit

时间:2016-10-05 03:44:45

标签: java timeunit

我查看了TimeUnittoMillis()方法。

 public long toMillis(long paramLong)
 {
    throw new AbstractMethodError();
 }

toMillis()方法除了抛出AbstractMethodError异常外什么都不做。

那么,toMillis()方法如何将秒,分钟等转换为毫秒?

3 个答案:

答案 0 :(得分:7)

TimeUnit中的每个值基本上都会覆盖它。你永远不会最终调用该实现,因为你永远不会引用TimeUnit类型的对象 - 它总是一个代表其中一个值的子类。

答案 1 :(得分:3)

打开TimeUnit并查看里面的常量......

/**
 * Time unit representing one thousandth of a microsecond
 */
NANOSECONDS {
    public long toNanos(long d)   { return d; }
    public long toMicros(long d)  { return d/(C1/C0); }
    public long toMillis(long d)  { return d/(C2/C0); }
    public long toSeconds(long d) { return d/(C3/C0); }
    public long toMinutes(long d) { return d/(C4/C0); }
    public long toHours(long d)   { return d/(C5/C0); }
    public long toDays(long d)    { return d/(C6/C0); }
    public long convert(long d, TimeUnit u) { return u.toNanos(d); }
    int excessNanos(long d, long m) { return (int)(d - (m*C2)); }
},

/**
 * Time unit representing one thousandth of a millisecond
 */
MICROSECONDS {
    public long toNanos(long d)   { return x(d, C1/C0, MAX/(C1/C0)); }
    public long toMicros(long d)  { return d; }
    public long toMillis(long d)  { return d/(C2/C1); }
    public long toSeconds(long d) { return d/(C3/C1); }
    public long toMinutes(long d) { return d/(C4/C1); }
    public long toHours(long d)   { return d/(C5/C1); }
    public long toDays(long d)    { return d/(C6/C1); }
    public long convert(long d, TimeUnit u) { return u.toMicros(d); }
    int excessNanos(long d, long m) { return (int)((d*C1) - (m*C2)); }
},

正如您将看到的,枚举器TimeUnit中的每个常量 NANOSECONDS,MICROSECONDS 等实现匿名方法,让您间接访问toMillis()因此此方法

 public long toMillis(long duration) {
        throw new AbstractMethodError();
    }
您的代码永远不会直接访问

...

答案 2 :(得分:2)

这是方法覆盖。

您可以在NANOSECONDS,MICROSECONDS等中看到覆盖的实现。