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?]
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?]
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:
import tec.uom.se.ComparableQuantity;
import tec.uom.se.format.SimpleUnitFormat;
import tec.uom.se.quantity.Quantities;
import javax.measure.quantity.Angle;
import static tec.uom.se.unit.Units.DEGREE_ANGLE;
import static tec.uom.se.unit.Units.RADIAN;
public class CustomLabelForDegrees {
public static void main(String[] args) {
ComparableQuantity<Angle> x = Quantities.getQuantity(2.009880307999, RADIAN).to(DEGREE_ANGLE);
System.out.println(x);
SimpleUnitFormat.getInstance().label(DEGREE_ANGLE, "°");
System.out.println(x);
SimpleUnitFormat.getInstance().label(DEGREE_ANGLE, "☯");
System.out.println(x);
SimpleUnitFormat.getInstance().label(DEGREE_ANGLE, "degrees");
System.out.println(x);
}
}
This prints:
115.15765897479669 [rad?]
115.15765897479669 °
115.15765897479669 ☯
115.15765897479669 degrees
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With