christopher
christopher

Reputation: 75

Is it possible to delay the loading of a class, that might be loaded dynamically later?

I'm wondering, and I have tried a myriad of convoluted search terms to determine if there was a way to delay the loading of a class in Java. What I mean is, the classes can be found on the class/build path, but I don't want them loaded at launch time. This results in the wrong class loader being used.

Can I, selectively or not, delay or prevent the default class loader from loading certain classes/JARs?

Example (with the 3rd party jar on the build path):

// boilerplate main
JarWrapper apiJar = SpecialJarLoader("api.jar"); // SpecialJarLoader is a proprietary class loader
Class apiClass = apiJar.loadClass("org.company.comm.AConnection"); // runtime failure here due to the class already being loaded

If I remove the Jar from the build path, apiClass.getClassLoader() is the proprietary loader as expected. The issue is that I am not free to use "org.company.comm.AConnection" or any other classes in the Jar (including the IDE's autocomplete), because it's not actually on the build path.

Upvotes: 4

Views: 1313

Answers (2)

Aniket Inge
Aniket Inge

Reputation: 25705

The only way to do that is to write your CUSTOM JAVA loader using JNI(that is, in C)

This way, you can SELECTIVELY load a class.

Upvotes: 0

Itay Maman
Itay Maman

Reputation: 30733

Classes are loaded only when they are first used. Thus your class will not be loaded at launch time but rather at the first time something from this class (including a static method, type declaration, etc.) is needed. Thus, the default behavior is that loading as delayed as long as possible.

If you want to control the loading time you can load the class explicitly via ClassLoaer.loadClass(). If your class is wrapped with some interface, you can have the code access only on the interface (thus ensuring the class is not loaded by some chain of dependencies) and then load it (ClassLoader.loadclass()) & instantiate it when you actually need an instance of this class.

Upvotes: 5

Related Questions