Problem Introduction
I'm trying to use this implementation of the Java Units of Measurement (JSR 363).
I would like to change the behavior of several of the provided units. An example of one is DEGREE_ANGLE
, so that the degree symbol (°) is appended to the end of any Quantity being toString
'd. As it is right now, the quantity will print 6.1345983929 [rad?]
An attempt at a Solution
I've tried plenty of different ways to achieve this, but it seems that one way which is present in other examples of AbstractSystemsOfUnits
(like from this Unified Code for Units of Measure implementation) is to use a static block like the following:
// //////////////////////////////////////////////////////////////////////////
// Label adjustments for UCUM system
static {
SimpleUnitFormat.getInstance().label(ATOMIC_MASS_UNIT, "AMU");
SimpleUnitFormat.getInstance().label(LITER, "l");
SimpleUnitFormat.getInstance().label(OUNCE, "oz");
SimpleUnitFormat.getInstance().label(POUND, "lb");
}
I've tried to adapt this solution by extending the Units
class of the implementation I'm using.
public final class MyUnits extends Units {
static {
SimpleUnitFormat.getInstance().label(DEGREE_ANGLE, "°");
}
}
And a simple test trying to use this extension:
Quantities.getQuantity(2.009880307999, MyUnits.RADIAN).to(MyUnits.DEGREE_ANGLE).toString();
Gives me 115.157658975 [rad?]
Question
How can I change the label on a Unit using the JSR 363 API?
Hmm I gave it a shot and got no issue with the base approach you describe, with that library you use (version 1.0.7)... Have I missed something?
No need to extend, the base approach works, here is an example:
This prints:
You can do that anywhere you want, anytime. It's usually done in a static block in order to be done once, early enough, but it's not a requirement.