首页 > 解决方案 > 从速度转换为(速度)^-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)

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

有人可以提供一个例子吗?

标签: javaunits-of-measurement

解决方案


速度定义为距离除以时间,因此您不能创建Speed“分钟每公里”的单位。但是,您可以创建自己的反向速度测量,这只不过是一个标记界面:

public interface InverseSpeed extends Quantity<InverseSpeed> {}

然后创建这样一个单元:

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

推荐阅读