Subhu.rys
Subhu.rys

Reputation: 25

How to ensure that a java class is loaded at application startup itself?

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.

Upvotes: 1

Views: 2264

Answers (2)

Stanislav Lukyanov
Stanislav Lukyanov

Reputation: 2157

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.

Upvotes: 2

giddi
giddi

Reputation: 103

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.

Upvotes: -1

Related Questions