0

I'm building a Java package and I need some initialization code to be called in order for the package to work properly. The package is being wrapped up as a .jar, and I have no control over what the user will be calling when they import my package into their application. Rather than having them need to call an initialization method before they can start using my package, is there any way for this method to be called under the hood?

I'd also like to mention that the static { } approach won't work, as I need this code to be called one time regardless of which objects in the package are being utilized.

George Morgan
  • 669
  • 10
  • 23

2 Answers2

1

No, there is no such method on the package level.

To achieve that you can add

static {
   ....
}

block to each of your classes and have that static block call common initializer.

For example:

package a.b;
class X {
  static {
     a.b.Static.init();
  }
}

class Y {
  static {
     a.b.Static.init();
  }
}

class Static {
  static void init() {
    ... my init code goes here ...
  }
}
iceraj
  • 359
  • 1
  • 5
  • Sorry, must have made the addendum to my post after you wrote up your answer. I need this code to be called one time regardless of which objects in the package are being utilized. There's really no way to accomplish this? – George Morgan Mar 29 '15 at 01:39
1

How many classes are in your .jar? If there aren't many, you could have a static block in each of your classes that calls your initialization logic. Like so:

static{
  MyInitializer.DoStuff();
}

class MyInitializer{
  static boolean hasInitialized = false;
  public static void DoStuff(){
    if(!hasInitialized){
      hasInitialized = true;
      //initialization logic
    }
  }
}
Quicksilver002
  • 735
  • 5
  • 12