1

I have a class extending Jscience's SystemOfUnits to define some custom units. I want this class to be loaded by JVM even before any call to method Unit.valueOf() is invoked.

if the class is not loaded in JVM then below invocation fails as java.text.ParseException: dz not recognized (in dz at index 0)

 Unit.valueOf("dz");

-

 public final class CustomUnits extends SystemOfUnits {

 ...

 private static HashSet<Unit<?>> UNITS = new HashSet<Unit<?>>();

 public static final Unit<Dimensionless> DOZEN = customUnits(Unit.ONE
        .times(12));

 public static final Unit<Dimensionless> PIECE = customUnits(DOZEN
        .divide(12));

 static {
    UnitFormat.getInstance().label(CustomUnits.DOZEN, "dz");
    UnitFormat.getInstance().label(CustomUnits.PIECE, "pcs");
 }

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

 ....
 }

Also be informed that this class will be part of a common jar which will be available as dependency to other main applications and i don't want every user to be informed that this class should be referred somewhere before Unit.valueOf() is called.

Looking for possible options that would enable a class to be loaded when the jar containing the custom class is loaded as dependency.

Wondering would spring bean initializing would be helpful.

Subhu.rys
  • 25
  • 1
  • 7

2 Answers2

2

Generally, there is no options to tell JVM when to load a class. Class will be loaded only when some other class refers it.

Moreover, AFAIU you need CustomUnits not just to be loaded but to be initialized (to run static constructor). Initialization can be triggered by using static members of class as well as instance creation.

As a workaround, you can call Class.forName(...) method - it also guarantees class to be fully loaded and initialized.

Stanislav Lukyanov
  • 2,147
  • 10
  • 20
  • I agree that Class.forName(..) could be used. But i don't what this to be informed to every users of the project. I decided to expose a static method CustomUnits.valueOf() which would in turn use Unit.valueOf(). Ensuring that the Custom class is loaded and initialized. – Subhu.rys Dec 13 '14 at 06:20
-1

Did you try specifying the jar (with SystemOfUnits class) as dependency to your common jar containing the custom class?
You can add these dependency in jar's Manifest file.

giddi
  • 103
  • 5