Pacerier
Pacerier

Reputation: 89613

How do we Load Classes on JVM start (straight away)?

Good afternoon all,

I was wondering is there anyway to make the static block of a class run even when the class itself is not referenced?

I am aware that that it is lazily loaded such that simply calling any of the functions of that class will start initiating the class,

However I want the class to be initiated prior any calls, in other words I want it to run on JVM start regardless of whether or not it is referenced.

Preloading java classes/libraries at jar startup suggested a workaround, but its not really the solution I'm looking for (basically I don't want to need to do a Class.forName, I want it to be done on JVM start)

How would we go about doing it?

Upvotes: 1

Views: 2573

Answers (1)

thkala
thkala

Reputation: 86333

If there is a way to do this, it would probably involve the use of JVM options, which is not exactly elegant or completely portable.

Using a wrapper class around your existing application might be a cleaner alternative, if all you need is for some class to be initialized before your actual application code is executed:

public class LoggedLauncher {
    public static void main(String[] args) {
        // Do whatever you need to initialize your logging class
        //
        // e.g. call a static method:
        //
        // MyLogger.init();

        // ...then start your application
        MyApplication.main(args);
    }
}

You might even use a bit of reflection so that the application class can be supplied as an argument to the wrapper, replacing the hard-coded reference. If you do so, don't forget to manipulate the args array so that the proper arguments will passed over to the main() method of your application.

Upvotes: 2

Related Questions