is there a UnitFactory Class available?
zifnab87 opened this issue · 3 comments
I am curious if there is a factory available that will return Units based on their standard string names
e.g
if it is "m" it should return Units.METRE
if it is "km" it should return MetricPrefix.KILO(Units.METRE)
UnitFactory.getUnit("m") => Units.METRE
Thanks!
Yes, but following conventions by other JSRs like 354 or 310 (in the JDK) it is not a "factory" here but "parser" or formatter. https://github.com/unitsofmeasurement/unit-ri/blob/master/src/main/java/tec/units/ri/AbstractUnit.java contains a parse()
method for
AbstractUnit.parse("m") => Units.METRE
It is a convenience method for UnitFormat.parse()
which allows greater control e.g. some implementations (Java SE based, not the RI by default) may also parse based on a locale and take other string representations like "Metre" (UK) or "Meter" (US, DE) into consideration, too.
In AbstractUnitFormat
and derived classes beside the label()
method there is also alias()
, so as it was asked in another ticket, this way you may add further strings to a particular unit e.g. "meter" or something that makes sense for your application. In the RI that is language neutral, so it's up to you which aliases you assign to a particular unit. In other implementations this may also work per locale.
Does that answer your question? Then feel free to close it (or tell us to)
awesome thanks! a couple more things:
What if I need to support non-conventional MetrixPrefix + Unit combinations - e.g Mega-metre - could those be handled?
What if I need to have access to other non-SI units e.g BYTE, Inch etc? if I import the uom-systems that have those units how can I have the parsing be done in such a way that it will work across nonSI and SI units? Btw I didnt find any support for calorie/kilocalorie (kcal) did I just miss it? thanks again!
For all known prefixes yes, so things like 'cm', 'mm', etc. are known to work. The best open solution under a free license (others like ISO are subject to its commercial license, we cannot offer those for free without violating the IP of ISO) would be Unicode CLRD which supports BIT or BYTE too. As well as Imperial or USCustomary systems that are available in uom-systems-common. All of these unit systems register with their implementation, e.g. uom-systems-common does with the RI, uom-systems-common-java8 does with the Java SE 8 port uom-se, therefore the default SimpleUnitFormat
has those units registered by default and should parse them. If you find a problem with any of those, please file a similar issue under https://github.com/unitsofmeasurement/si-units/issues or https://github.com/unitsofmeasurement/uom-systems/issues. Thanks