在 2 个实体之间进行转换时,通常通过UnitConverter进行。我应该如何找出转换因子是多少?例如:
public static final Unit<Length> KILOMETRE = METER.times(1000);
public static final Unit<Length> CENTIMETRE = METRE.divide(100);
我想从转换器接口以编程方式获取转换因子(即 1000 b/w KILOMETER 和 METER 或 1/100,如果 CENTIMETER 到 METRE)
我不确定如何从 UnitConverter 界面获取此信息。
编辑1
protected double getConvFactor(Unit<Length> from, Unit<Length> to) {
double factor = -1;
UnitConverter unitConverter = from.getConverterTo(to);
if (unitConverter instanceof MultiplyConverter) {
MultiplyConverter multiplyConverter = (MultiplyConverter) unitConverter;
factor = multiplyConverter.getFactor();
} else if (unitConverter instanceof AddConverter) {
AddConverter addConverter = (AddConverter) unitConverter;
factor = addConverter.getOffset();
} else if (unitConverter instanceof RationalConverter) {
RationalConverter rationalConverter = (RationalConverter) unitConverter;
double divisor = rationalConverter.getDivisor().doubleValue();
double dividend = rationalConverter.getDividend().doubleValue();
factor = divisor;
}
}