我看了看TimeUnit
和toMillis()
方法。
public long toMillis(long paramLong)
{
throw new AbstractMethodError();
}
toMillis()
AbstractMethodError
方法除了抛出异常什么都不做。
那么,toMillis()
方法如何将秒、分钟等转换为毫秒?
TimeUnit
基本上,其中的每个值都会覆盖它。您永远不会最终调用该实现,因为您永远不会引用类型对象TimeUnit
- 它始终是表示其中一个值的子类。
打开 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();
}
您的代码永远不会直接访问...
它是方法覆盖。
您可以在 NANOSECONDS、MICROSECONDS 等中看到被覆盖的实现。