blogger templates blogger widgets
This is part of a list of blog posts.
To browse the contents go to

Class loading problems


Short note on java class loading mechanism:

When the JVM boots up at runtime, the bootstrap classloader (also sometimes called the primordial classloader) loads Java's core API (rt.jar). It then calls the "extension" classloader, which loads all the classes that are in the /jre/lib/ext directory of your Java installation. After the extensions directory loads, the system classloader loads any classes on your system's classpath, as specified in your individual personal profile or the OS environmental classpath variable for the system.

As the developer, you control the only other two ways in which additional classes can be loaded.

One means of control is using the command line '– classpath' argument to specify additional jar files or directories that the program should consult for class resources.

The other way is explicitly instantiating a classloader in your application and specifying the URL to the resources you wish to load. (I mention this last option only for completeness. It is outside the scope of this article. Consult the Related Resources section of this article for further reading.)



Delegation model

Java's classloading mechanism works on a delegation model. In practice, this means that as each classloader prepares to load a class it checks whether a class of that particular name was loaded by any of its parent classloaders. If the class was loaded by a parent classloader then the currently active classloader uses the already loaded class. Otherwise, it loads the requested class for the first time.

Let's say I have a project that includes a jar library.

Both the project and the jar library includes a class com.lang.SpecialStr.

//to test
public static void main(String[] args) {
SpecialStr s = new SpecialStr();
s.valueOf();
ClassLoader classLoader = TestClient.class.getClassLoader();
System.out.println(classLoader.getResource("com/lang/SpecialStr.class"));
}

By default your class loads the one that's in your project. This is because the default class loading order is defined as:

Output:
file:/C:/Users/Administrator/IBM/rationalsdp/workspace/TestClient/bin/com/lang/SpecialStr.class

Change the class loading order to load the jar's class.

Output:
jar:file:/C:/Users/Administrator/Desktop/specialStr.jar!/com/lang/SpecialStr.class

No comments:

Post a Comment