Java ClassLoader (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:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
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.

Java ClassLoader (3) – Namespaces

In this third part of series about Java ClassLoader we will show how class loaders interact with namespaces in Java, and how using class loaders it is possible to have two or more instances of a static field.

In the previous article we learned how to change a class’ class loader. Can we do anything interesting now, that we know how to do it? We could use it for example to divide our program into two namespaces. Every different class loader represents a different namespace. Static fields of classes inside one namespace are separate from static fields of classes from other namespaces. If we set a value of a specific static field in namespace A, objects from namespace B will not be able to read it, and vice versa.

Let’s see how it works. We will have a public static Integer field in some class, and we will be trying to access this field from classes loaded with different class loaders. Here is this field:

1:
2:
3:
4:
5:
6:
7:
8:
public class StaticHolder {
    /**
     * Static variable with default value of null. (Normally it
     * would be good to have getter and setter methods here,
     * but this time we will not declare them, in sake of simplicity.)
     */
    public static Integer value = null;
}

Below is also the class used to access the field. It will read the value of the field and then change it to 4. Default value for any class field is null, so that’s what we expect to see as the start value. In a normal, single-classloader program, after changing the value of the static field, the change would be visible to other objects reading that field. We will see what happens with multiple classloaders.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
public class StaticAccessor {
    /**
     * Accesses the static field from StaticHolder class.
     * It reads its value and after that sets it to 4.
     */
    @Override
    public void runMe() {
        System.out.println("--- Starting runMe. Static value: "
            + StaticHolder.value);
        StaticHolder.value = 4;
        System.out.println("--- Finishing runMe. Static value: "
            + StaticHolder.value);
    }
}

In our experimental main method we will create this time two CustomClassLoaders and load our StaticAccessor field with both of them. We will then create two instances of the StaticAccessor class, each of them from the different class loader, and run their runMe() methods.

You can find the implementation of our CustomClassLoader in the previous article.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
public class StaticAccessorTest {
    /**
     * This main method shows what happens when we load two
     * classes with two different ClassLoader's and access
     * some other class' static field from them.
     */
    public static void main(String... strings) throws Exception {
        // Using the first ClassLoader
        CustomClassLoader loader1 =
            new CustomClassLoader(StaticAccessorTest.class.getClassLoader());
        Class<?> clazz1 = loader1.loadClass("javablogging.StaticAccessor");
        Object instance1 = clazz1.newInstance();
        clazz1.getMethod("runMe").invoke(instance1);

        // Using the second ClassLoader
        CustomClassLoader loader2 =
            new CustomClassLoader(StaticAccessorTest.class.getClassLoader());
        Class<?> clazz2 = loader2.loadClass("javablogging.StaticAccessor");
        Object instance2 = clazz2.newInstance();
        clazz2.getMethod("runMe").invoke(instance2);
    }
}

When we run the program, we will get the following output:

loading class 'javablogging.StaticAccessor'
...
--- Starting runMe. Static value: null
loading class 'java.lang.Integer'
--- Finishing runMe. Static value: 4
loading class 'javablogging.StaticAccessor'
...
--- Starting runMe. Static value: null
loading class 'java.lang.Integer'
--- Finishing runMe. Static value: 4

When you look at the “— Starting runMe” lines, you will notice that both of them show null! Although we changed the static field to 4 in the first run of runMe(), the value read in the second runMe() shows once again null. The reason for it is that we have now two separate namespaces, as on the image below:





In normal programs it may be hard to see a usage for such tricks. Separating namespaces in such a way may be however useful for example when doing unit tests, when you want to be sure that every test runs in a completely separate sandbox, or when implementing frameworks or application servers, where every deployed application should be isolated from others.

You can read more about class loaders and namespaces in Java for example in this article: http://www.artima.com/underthehood/classloadersP.html.

Java ClassLoader (2) – Write your own ClassLoader

This is the second part of series of articles about Java’s ClassLoader. We will show here how you can write your own simple ClassLoader and “replace” the default system ClassLoader with your version.

We have to extend the java.lang.ClassLoader class and implement some of its crucial methods, like loadClass(String name). This method is run every time somebody requests a class inside the code, and receives as a parameter the full name of the class to load. In our implementation we will print out this name, so to know when our method was called, and then load the class with our class loader if the class is in “javablogging” package. If the class is not in “javablogging”, we will use the super.loadClass() method, which will pass the request to the parent class loader. (Please note that in this article we omit the “package” and “import” statements to make the code shorter, but every class should be inside the “javablogging” package).

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
/**
 * Our custom implementation of the ClassLoader.
 * For any of classes from "javablogging" package
 * it will use its {@link CustomClassLoader#getClass()}
 * method to load it from the specific .class file. For any
 * other class it will use the super.loadClass() method
 * from ClassLoader, which will eventually pass the
 * request to the parent.
 *
 */
public class CustomClassLoader extends ClassLoader {

    /**
     * Parent ClassLoader passed to this constructor
     * will be used if this ClassLoader can not resolve a
     * particular class.
     *
     * @param parent Parent ClassLoader
     *              (may be from getClass().getClassLoader())
     */
    public CustomClassLoader(ClassLoader parent) {
        super(parent);
    }

    /**
     * Loads a given class from .class file just like
     * the default ClassLoader. This method could be
     * changed to load the class over network from some
     * other server or from the database.
     *
     * @param name Full class name
     */
    private Class<?> getClass(String name)
        throws ClassNotFoundException {
        // We are getting a name that looks like
        // javablogging.package.ClassToLoad
        // and we have to convert it into the .class file name
        // like javablogging/package/ClassToLoad.class
        String file = name.replace('.', File.separatorChar)
            + ".class";
        byte[] b = null;
        try {
            // This loads the byte code data from the file
            b = loadClassData(file);
            // defineClass is inherited from the ClassLoader class
            // and converts the byte array into a Class
            Class<?> c = defineClass(name, b, 0, b.length);
            resolveClass(c);
            return c;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Every request for a class passes through this method.
     * If the requested class is in "javablogging" package,
     * it will load it using the
     * {@link CustomClassLoader#getClass()} method.
     * If not, it will use the super.loadClass() method
     * which in turn will pass the request to the parent.
     *
     * @param name
     *            Full class name
     */
    @Override
    public Class<?> loadClass(String name)
        throws ClassNotFoundException {
        System.out.println("loading class '" + name + "'");
        if (name.startsWith("javablogging.")) {
            return getClass(name);
        }
        return super.loadClass(name);
    }

    /**
     * Loads a given file (presumably .class) into a byte array.
     * The file should be accessible as a resource, for example
     * it could be located on the classpath.
     *
     * @param name File name to load
     * @return Byte array read from the file
     * @throws IOException Is thrown when there
     *               was some problem reading the file
     */
    private byte[] loadClassData(String name) throws IOException {
        // Opening the file
        InputStream stream = getClass().getClassLoader()
            .getResourceAsStream(name);
        int size = stream.available();
        byte buff[] = new byte[size];
        DataInputStream in = new DataInputStream(stream);
        // Reading the binary data
        in.readFully(buff);
        in.close();
        return buff;
    }
}

For a bunch of classes from the “javablogging” package (we will see one of them in a minute) we will load them ourselves from the .class files instead of passing a request for them to the parent class loader. We do it for two reasons: first is to show that in a real-world example you could easily implement the getClass() method to load the class code from some other source, like from the TCP/IP connection or from the database, second is that when we load the class directly in our class loader, instead of passing further the request, our class loader will become default class loader for the newly created class. It will be returned every time from the class.getClassLoader() method and every new request for a class, from an instance of the created class, will pass through our class loader.

It may seem a little confusing, so let’s see how it works on an example. We will load a class using this class loader, and from inside the class we will access some other class, which could be anything, like java.util.Integer.

The runMe() method of the class below simply creates an instance of Integer class and prints it to the console. We will load this class in a minute with our class loader.

1:
2:
3:
4:
5:
6:
7:
8:
public class IntegerPrinter {
    /**
     * Creates an instance of Integer class and prints it.
     */
    public void runMe() {
        System.out.println(new Integer(4));
    }
}

Now the main method that will do our experiment. We create there an instance of our custom class loader, and load our IntegerPrinter class with it using the full class name “javablogging.IntegerPrinter”. We then create a new instance of the IntegerPrinter and run its runMe() method using Reflection.

Note that we could NOT cast ‘instance’ at this point to IntegerPrinter and run its ‘runMe’ method directly, because we would get a ClassCastException! It would say something like “could not cast javablogging.IntegerPrinter to javablogging.IntegerPrinter” which seems very weird, but has good reasons. We loaded the IntegerPrinter class with our custom class loader, but the variable of type IntegerType which we would declare in IntegerPrinterTest would have been loaded with the default system class loader. To the JVM they would be classes from different namespaces, hence impossible to cast one to another. More on that in next articles.

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
public class IntegerPrinterTest {
    /**
     * This main method shows a use of our CustomClassLoader for
     * loading some class and running it. All the objects referenced
     * from the IntegerPrinter class will be loaded with
     * our CustomClassLoader.
     */
    public static void main(String[] args) throws Exception {
        CustomClassLoader loader = new CustomClassLoader(
            StaticAccessorTest.class.getClassLoader());
        Class<?> clazz =
            loader.loadClass("javablogging.IntegerPrinter");
        Object instance = clazz.newInstance();
        clazz.getMethod("runMe").invoke(instance);
    }
}

When we run our main method, we will get following output:

loading class 'javablogging.IntegerPrinter'
loading class 'java.lang.Object'
loading class 'java.lang.System'
loading class 'java.lang.Integer'
loading class 'java.io.PrintStream'
4

First line is obvious, because we called ourselves the loadClass() method of our class loader. But where do the other lines come from? We did not call loadClass() for them. Since our class loader became the default class loader for the created class, every request for any other class from inside IntegerPrinter will go through our CustomClassLoader. We dont have to call loadClass() any more, it will be called automatically by the JVM! When you look at IntegerPrinter’s code, you will see that we use there System class, and its “out” variable which is of type PrintStream. We also create an Integer, and since IntegerPrinter, like any other class, extends java.lang.Object, we also have to load the Object class. All these requests go now through our CustomClassLoader.

One important thing to understand here is that we replaced the default system class loader only for one loaded class – IntegerPrinter. What we did has still no influence on default class loader used for example by class IntegerPrinterTest with its main method. There is however a way to replace the class loader even before running the main method, and we will show it in one of next articles.

Please note, that if you were about to write a real-world class loader, you would probably extend the URLClassLoader, because the part of loading a class from a file is there already implemented. Also, real class loaders normally ask their parent to load a class BEFORE trying to load it themselves. In our example, for the classes in “javablogging” package, we do load them without asking the parent. We will need that behavior in examples in next parts of this series, where we will talk about namespaces, so stay tuned!.