Search code examples
javaphysicsjscience

Using moment of inertia in jscience


I'm using jscience in a simple physics calculator I'm making. I need to calculate a moment of inerta given some gears and rotating cylinders.

I prefer to use jscience, but it seems jscience does not have a measure of moment of inertia? Or is moment of inertia represented as something else? From these formulas I get that a moment of inertia can be described by kg*m^2.

Looking at the other quantity interfaces in jscience, I tried mimicking the "Mass" interface and created my own quantity interface named "MomentOfInertia":

package jscience;

import javax.measure.quantity.Quantity;
import javax.measure.unit.Unit;

public interface MomentOfInertia extends Quantity {

    public final static Unit<MomentOfInertia> UNIT = 
        SI.KILOGRAM.times(SI.SQUARE_METRE).asType(MomentOfInertia.class);

}

Next I'm trying to define a moment of inertia:

public static void main(String[] args) throws Exception {
    Amount<MomentOfInertia> moi = Amount.valueOf(1000,
        SI.KILOGRAM.times(SI.SQUARE_METRE).asType(MomentOfInertia.class));

    System.out.println(moi);
}

However, this won't run without throwing the following exception:

Exception in thread "main" java.lang.ExceptionInInitializerError
at sun.misc.Unsafe.ensureClassInitialized(Native Method)
    at sun.reflect.UnsafeFieldAccessorFactory.newFieldAccessor(UnsafeFieldAccessorFactory.java:43)
    at sun.reflect.ReflectionFactory.newFieldAccessor(ReflectionFactory.java:142)
    at java.lang.reflect.Field.acquireFieldAccessor(Field.java:1088)
    at java.lang.reflect.Field.getFieldAccessor(Field.java:1069)
    at java.lang.reflect.Field.get(Field.java:393)
    at javax.measure.unit.Unit.asType(Unit.java:170)
    at test.Test.main(Test.java:8)
Caused by: java.lang.NullPointerException
    at javax.measure.unit.Unit.asType(Unit.java:174)
    at jscience.MomentOfInertia.<clinit>(MomentOfInertia.java:10)
    ... 8 more

TLDR: (How) can I define a moment of inertia in jscience?


Solution

  • I am unfamiliar with JScience, but look at the way Torque is defined:

    public interface Torque extends Quantity {
        public final static Unit<Torque> UNIT = 
            new ProductUnit<Torque>(SI.NEWTON.times(SI.METRE));
    }
    

    The issue that you are having here is one of cyclical initialization: you are calling asType to get the value you will assign to MomentOfInertia.UNIT, but asType(MomentOfInertia.class) requires the value of MomentOfInertia.UNIT, which is currently null, because it has not been assigned.

    So, something like the following might work:

    public interface MomentOfInertia extends Quantity {
    
        public final static Unit<MomentOfInertia> UNIT = 
            new ProductUnit<MomentOfInertia>(SI.KILOGRAM.times(SI.SQUARE_METRE));
    
    }