Loading Classes directly from JAR files

Whenever a class is referenced in a java program it is loaded using JVM’s bootstrap class loader. This often becomes a problem when two different classes with same name and same package declaration are to be loaded. For example relying on JVM’s class loader one cannot load two different versions of the same JDBC driver. So how to get around this problem? The answer lies in making a custom class loader and loading classes directly from JAR archives. See the code snippet below:

import java.net.*;

URL url=new URL("jar:file:/c:myJarsmyJar1.jar!/");
URLClassLoader ucl = URLClassLoader(new URL[] { url });
Object myClassObject = Class.forName("MyClass", true, ucl).newInstance();

This example illustrates how to load java classes from their respective jar files using URLClassLoader. There are other APIs also available for this purpose like Jar Class Loader (JCL), which also provides Spring integration.

Leave a Reply