URLClassLoader

java.net.URLClassLoader Example

In this example we shall show you how to make use of URLClassLoader, This class can be used to load a Class or a collection of classes that are accessible via URLs which referring to both JAR files and directories. Any URL that ends with a ‘/’ is assumed to refer to a directory. Otherwise, the URL is assumed to refer to a JAR file which will be opened as needed.

Now, let’s see how to dynamically load a Class via the URLClassLoader class.

 

 

1. Example (using loadClass):

Bean.java:

package com.jcg;

/**
 * @author ashraf
 *
 */
public class Bean {
	
	public void sayHello() {
		System.out.println("Hello from loaded Bean class !!!");
	}

}

URLClassLoaderTest.java:

package com.jcg;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @author ashraf
 *
 */
public class URLClassLoaderTest {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		
		// Getting the jar URL which contains target class
		URL[] classLoaderUrls = new URL[]{new URL("file:///home/ashraf/Desktop/simple-bean-1.0.jar")};
		
		// Create a new URLClassLoader 
		URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);
		
		// Load the target class
        Class<?> beanClass = urlClassLoader.loadClass("com.jcg.Bean");
        
        // Create a new instance from the loaded class
        Constructor<?> constructor = beanClass.getConstructor();
        Object beanObj = constructor.newInstance();
        
        // Getting a method from the loaded class and invoke it
        Method method = beanClass.getMethod("sayHello");
        method.invoke(beanObj);

	}

}

Output:

Hello from loaded Bean class !!!

In the above example, we created a simple-bean jar file, contains a Bean class with sayHello method which print a message to the console. Also, we created another URLClassLoaderTest class which loads our Bean class using the simple-bean.jar URL via URLClassLoader then creates a new instance from it and finally invoking the sayHello method.

Tip

  • The AccessControlContext of the thread that created the instance of URLClassLoader will be used when subsequently loading classes and resources.
  • The classes that are loaded are by default granted permission only to access the URLs specified when the URLClassLoader was created.

There is another way to dynamically load a Class via reading the .Class file and instantiate an instance from it then invoking its methods, Let’s see the below example.

2. Example (using getResourceAsStream):

ClassLoaderInput.java:

package com.jcg;

public class ClassLoaderInput {
	public void printString() {
		System.out.println("Hello world from the loaded class !!!");
	}
}

JavaClassLoaderTest.java:

package com.jcg.cl;

import java.io.InputStream;

public class JavaClassLoaderTest extends ClassLoader {

	public static void main(String args[]) throws Exception {
		JavaClassLoaderTest javaClassLoader = new JavaClassLoaderTest();
		javaClassLoader.load();

	}

	public void load() throws Exception {

		// create FileInputStream object
		InputStream fileInputStream = this.getClass().getClassLoader().getResourceAsStream("ClassLoaderInput.class");

		/*
		 * Create byte array large enough to hold the content of the file. Use
		 * fileInputStream.available() to determine size of the file in bytes.
		 */
		byte rawBytes[] = new byte[fileInputStream.available()];

		/*
		 * To read content of the file in byte array, use int read(byte[]
		 * byteArray) method of java FileInputStream class.
		 */
		fileInputStream.read(rawBytes);

		// Load the target class
		Class<?> regeneratedClass = this.defineClass(rawBytes, 0, rawBytes.length);

		// Getting a method from the loaded class and invoke it
		regeneratedClass.getMethod("printString", null).invoke(regeneratedClass.newInstance(), null);
	}

}

Output:

Hello world from the loaded class !!!

In the above example, we created a ClassLoaderInput class, contains printString method which print a message to the console. Also, we created another JavaClassLoaderTest class which loads our ClassLoaderInput class via reading the byte array of its .class file InputStream then creates a new instance from it and finally invoking the printString method.

TipWe utilize the getResourceAsStream method of the ClassLoader class to get the InputStream of the .Class file from the resource directory.

3. Download the Source Code of this example:

This was an example of how to to dynamically load a Class is via the URLClassLoader class.

Download
You can download the full source code of this example here: java.net.URLClassLoader Example Code

Ashraf Sarhan

Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button