从速度转换为(速度)^-1

Convertion from Speed to (Speed)^-1

使用 javax.measure 库,我尝试将 km/h 转换为 min/km。

然而 min/km 不是 unit-ri 提议的单位的一部分。

所以我尝试创建自己的单元:MINUTE_BY_KILOMETERS

import javax.measure.Quantity;
import javax.measure.Unit;
import javax.measure.quantity.Length;
import javax.measure.quantity.Speed;

import tec.units.ri.quantity.Quantities;
import tec.units.ri.unit.MetricPrefix;
import tec.units.ri.unit.Units;
    Quantity<Speed> speed = Quantities.getQuantity(10, Units.KILOMETRE_PER_HOUR);
    assertEquals("10 km/h", speed.toString());

    // Conversion m/s
    assertEquals("2.7777800000000004 m/s", speed.to(Units.METRE_PER_SECOND).toString());

    // Conversion min/km
    Unit<Speed> MINUTE_BY_KILOMETERS = Units.MINUTE.divide(MetricPrefix.KILO(Units.METRE)).asType(Speed.class);
    assertEquals("6 min/km", speed.to(MINUTE_BY_KILOMETERS).toString());

但我得到一个例外:

java.lang.ClassCastException: The unit: min/km is not compatible with quantities of type interface javax.measure.quantity.Speed
    at tec.units.ri.AbstractUnit.asType(AbstractUnit.java:274)

我想我必须创建自己的类型,但我不知道如何创建。

有人可以提供示例吗?

速度定义为距离除以时间,因此您无法创建 "minutes per kilometer" 的 Speed 单位。但是,您可以创建自己的反速度测量值,它只不过是一个标记界面:

public interface InverseSpeed extends Quantity<InverseSpeed> {}

然后创建这样一个单元:

Unit<InverseSpeed> MINUTE_BY_KILOMETERS = 
    Units.MINUTE.divide(MetricPrefix.KILO(Units.METRE)).asType(InverseSpeed.class);

我终于发现有一个 .inverse 函数可以在需要时进行转换。

所以你必须在代码中保留(距离/时间)度量来完成所有的操作和转换,并在你想要你的值时在最后添加一个.inverse():

Unit<Speed> KILOMETERS_BY_MINUTES = MetricPrefix.KILO(Units.METRE).divide(Units.MINUTE).asType(Speed.class);
assertEquals("5.9999952000038395 min/km", speed.to(KILOMETERS_BY_MINUTES).inverse().toString());