Search code examples
javaclassloadjvmboot

Java - Load additional class at JVM startup


I'd like to load an additional class at JVM startup. Specifically, the class should be loaded after all core libraries are loaded (so after rt.jar and lib/ext at least).

The class isn't referenced anywhere. It contains a static block setting a JVM-wide proxy that we'd like all URL connections to use.

I've tried the -Xbootclasspath/a, -Xbootclasspath/p options. With -verbose:class added to JVM_OPTS as well the load/open output created by the -Xbootclasspath variant indicates all core libraries are "loaded" while my JAR is simply "opened".

Is there a way to force load a class - or better still all classes in a JAR - at JVM bootup after all core classes have loaded?


Solution

  • After research I couldn't find any better way than a custom classloader.

    Here's what I wrote. It inherently uses the default classloader for all classloading methods, but offers access to a non-static initializer where custom class loading/referencing can occur.

    public class CustomClassLoader extends ClassLoader {
    
        {
            // Custom class loading goes in this non-static initializer.
            loadClass("java.org.myorganisation.package.MyClass");
        }
    
        public CustomClassLoader() {
            super(CustomClassLoader.class.getClassLoader());
        }
    
        public CustomClassLoader(ClassLoader parent) {
            super(parent);
        }
    }
    

    Specify the custom class loader by defining system property -Djava.system.class.loader=com.anon.mypackage.CustomClassLoader.