UnitUtils { public static @Nullable String getDimensionName(Unit<?> unit) { for (Class<? extends SystemOfUnits> system : ALL_SYSTEM_OF_UNITS) { for (Field field : system.getDeclaredFields()) { if (field.getType().isAssignableFrom(Unit.class) && Modifier.isStatic(field.getModifiers())) { Type genericType = field.getGenericType(); if (genericType instanceof ParameterizedType) { String dimension = ((Class<?>) ((ParameterizedType) genericType).getActualTypeArguments()[0]) .getSimpleName(); Unit<?> systemUnit; try { systemUnit = (Unit<?>) field.get(null); if (systemUnit == null) { LOGGER.warn("Unit field points to a null value: {}", field); } else if (systemUnit.isCompatible(unit)) { return dimension; } } catch (IllegalArgumentException | IllegalAccessException e) { LOGGER.error("The unit field '{}' seems to be not accessible", field, e); } } else { LOGGER.warn("There is a unit field defined which has no generic type parametrization: {}", field); } } } } return null; }  static @Nullable Class<? extends Quantity<?>> parseDimension(String dimension); static @Nullable String getDimensionName(Unit<?> unit); static @Nullable Unit<?> parseUnit(@Nullable String pattern); static boolean isDifferentMeasurementSystem(Unit<? extends Quantity<?>> thisUnit, Unit<?> thatUnit); static final String UNIT_PLACEHOLDER; static final String UNIT_PERCENT_FORMAT_STRING; }
@Test public void testGetDimensionName() { assertThat(UnitUtils.getDimensionName(SIUnits.CELSIUS), is(Temperature.class.getSimpleName())); assertThat(UnitUtils.getDimensionName(SmartHomeUnits.KILOWATT_HOUR), is(Energy.class.getSimpleName())); assertThat(UnitUtils.getDimensionName(SmartHomeUnits.WATT), is(Power.class.getSimpleName())); assertThat(UnitUtils.getDimensionName(MetricPrefix.MEGA(SmartHomeUnits.KILOWATT_HOUR)), is(Energy.class.getSimpleName())); Unit<?> unit = UnitUtils.parseUnit("°F"); assertNotNull(unit); if (unit != null) { assertThat(UnitUtils.getDimensionName(unit), is(Temperature.class.getSimpleName())); } unit = UnitUtils.parseUnit("m"); assertNotNull(unit); if (unit != null) { assertThat(UnitUtils.getDimensionName(unit), is(Length.class.getSimpleName())); } }