Search code examples
javaunits-of-measurementjsr363

unit-of-measurement filter by quantity


we are using the great unit-of-measurement framework to manage units dynamically. I have the requirement to filter a list of units by quantity. E.g. display all mass (tonne, kg ....). The list results in an generic capture list (which is not ideal - i know). The generic information does not exist at runtime (only at compile time). However for the unit interface an implementation exists to check the compatibility exists:

  • boolean isCompatible(Unit that);

    @Test
    public void testCompatible_ByUnit(){
        Unit<Mass> kilogram = Units.KILOGRAM;
        Unit<Mass> tonne = NonSI.TONNE;
    
        assertTrue(kilogram.isCompatible(tonne));
    }
    

Is there any interface to check the compatiblity by quantity?

Non working example with quantity Mass.

    @Test
    public void testCompatible_FilterByQuantityAndCapture(){
        Unit<?> kilogram = Units.KILOGRAM;
        // wish: interface does not exist
        assertTrue(kilogram.isCompatible(Mass.class));
    }

Solution

  • This is a common problem of the Java language because Java so far does not offer Reified Generics.

    I'm not aware that this feature made it into Java SE 9, so we likely won't see it before Java 10 or later.

    <Q extends Quantity<Q>> Unit<Q> getUnit(Class<Q> quantityType);
    

    returns the default (or system) unit for a given Quantity class. And although Dimension is more of an "umbrella" to quantities, you may also get a list of all units under a particular dimension.

    Set<? extends Unit<?>> getUnits(Dimension dimension);
    

    In a future version of the API/SPI SystemOfUnits may also offer something similar for a Quantity class, but it is quite possible this kind of additional method won't make much sense before the underlying Java platform offers reified generics or some other way of better type information than it does toeday.