0

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));
    }
itstata
  • 1,058
  • 7
  • 17

1 Answers1

2

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.

Werner Keil
  • 592
  • 5
  • 12
  • Thank you - the workaround with the default (or system) unit for the quantity is working me. – itstata Jul 11 '17 at 07:23
  • I'm trying the getUnits() approach with the uom-ri library's `METRE` to essentially retrieve a list of Length-dimensioned units, and keep getting empty sets: `Set extends Unit>> units = system.getUnits(METRE.getDimension());` Any guidance on how I'm misusing the API? I really need this for a UI for entering/updating quantities. Thanks! – arpieb Jul 13 '17 at 15:33
  • Thanks for pointing that out. Did you use the RI or Java SE implementation? We'll try to replicate it and either tell how to change the call or if necessary fix issues. – Werner Keil Jul 14 '17 at 16:08