Search code examples
javaclassloader

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.


Solution

  • 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.