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.