How can I change the label on a module using the Java Measurement API?

Problem introduction

I am trying to use this implementation of Java Units of Measurement (JSR 363) .

I would like to change the behavior of several provided units. An example of one is DEGREE_ANGLE

, so the degree symbol (°) is added to the end of any quantity being toString

'd. As of now, the number will print6.1345983929 [rad?]

Attempted solution

I've tried many different ways to achieve this, but it seems like one of the ways that is present in other examples AbstractSystemsOfUnits

(for example from the Unified Code for Units of Measure ) is to use a static block like this:

// //////////////////////////////////////////////////////////////////////////
// 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 tried to adapt this solution by extending the class Units

implementation that I am 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 module using the JSR 363 API?

+3


source to share


1 answer


Hmm, I gave it a shot and had no problem with the basic approach you describe with the library you are using (version 1.0.7) ... Am I missing something?

No need to extend, basic approach works, here's 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);
    }
}

      



Prints:

115.15765897479669 [rad?]
115.15765897479669 °
115.15765897479669
115.15765897479669 degrees

      

You can do this anywhere, anytime. This is usually done in a static block to do it once, early enough, but this is not a requirement.

+4


source







All Articles