Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 615
karobar Avatar asked Jun 16 '17 20:06

karobar


1 Answers

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.

like image 68
Hugues M. Avatar answered Nov 14 '22 00:11

Hugues M.