Java ClassLoader – Part 4 – Loading a custom ClassLoader on JVM start

In a previous article of this series we learned how to replace the default system class loader for any given class. This time we will show how to replace it even before running the main method, so that the entire program runs from start with a custom class loader.

To do it, you should change the “java.system.class.loader” java environment variable to the full name of the class loader you want to use when running the program. Let’s create a simple program to demonstrate it. It will print out its own class loader:

public class SimpleMain {
    /**
     * If you run this main method supplying the
     * -Djava.system.class.loader=javablogging.CustomClassLoader
     * parameter, class SimpleMain will be loaded with
     * our CustomClassLoader. Every other
     * class referenced from here will be also loaded with it.
     */
    public static void main(String... strings) {
        System.out.print("This is my ClassLoader: "
            + SimpleMain.class.getClassLoader());
    }
}

Run this program the following way:

java -Djava.system.class.loader
    =javablogging.CustomClassLoader javablogging.SimpleMain

You will get the following output, proving that our classloader is active from the beginning:


loading class 'java.lang.System'

loading class 'java.nio.charset.Charset'

loading class 'java.lang.String'

loading class 'javablogging.SimpleMain'

loading class 'java.lang.Object'

loading class 'java.lang.StringBuilder'

loading class 'java.lang.Class'

loading class 'java.io.PrintStream'

This is my ClassLoader: javablogging.CustomClassLoader@42e816

As you can see, class javablogging.SimpleMain and all classes used in it were loaded with our CustomClassLoader. In contrary to the way in the previous article we did not have to specifically create now an instance of our class loader inside the code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s