4

I want to define a new distance unit in JScience. The "Tutorial" section of the project website just leads to Javadoc which, while fairly complete, is a bit too dense for me to fathom how I actually go about defining my own unit.

Could you provide an example?

Cheers.

Pete

razlebe
  • 7,134
  • 6
  • 42
  • 57

3 Answers3

5

I know this is an old post, but.. i'm going to post the answer anyways, maybe it'll be useful to someone

In order to define a custom unit in JScience, you have to extend the class SystemOfUnits and define here all your custom units.

Check the exemple below (i'm defining the unit for ACREs)

public class MyUnits extends SystemOfUnits 
{
   private static HashSet<Unit<?>> UNITS = new HashSet();

   private static final MyUnits INSTANCE = new MyUnits();

   public static final Unit<Area> ACRE = myUnits((SI.METER.pow(2)).times(4046.8564224).asType(Area.class));

   public static MyUnits getInstance()
   {
      return INSTANCE;
   }    

   @Override
   public Set<Unit<?>> getUnits()
   {
      return Collections.unmodifiableSet(UNITS);
   }

   private static <U extends Unit<?>> U myUnits(U unit)
   {
      UNITS.add(unit);
      return unit;
   }
}
Pierfrancesco Soffritti
  • 1,678
  • 1
  • 18
  • 22
  • I'm having the same question too.. I looked at their docs and I think what we need is http://jscience.org/api/javax/measure/unit/UnitFormat.html (label method), but I don't know how to implement it. – Ralphilius May 03 '15 at 16:22
1

perhaps this other SO question about units in Java can help.

Community
  • 1
  • 1
Jason S
  • 184,598
  • 164
  • 608
  • 970
0

Please have a look at how JSR 363 RI does this (the successor to 275 which was implemented by JScience 4) https://github.com/unitsofmeasurement/unit-ri/blob/master/src/main/java/tec/units/ri/format/SimpleUnitFormat.java

The default flavor of SimpleUnitFormat supports UTF-8, while ASCII is for limited environments or devices that may have no GUI or limited character sets:

DEFAULT.label(MetricPrefix.MICRO(Units.LITRE), "µl"); ASCII.label(MetricPrefix.MICRO(Units.LITRE), "microL");

Note, the label() method will be introduced to JSR 363 API in the next candidate release for Public Draft. Currently it's part of the RI (https://github.com/unitsofmeasurement/unit-ri, not JScience, though it may eventually migrate to the new standard, too in V5)

Werner Keil
  • 592
  • 5
  • 12