How to load classes which are not in your classpath

In certain scenario, you may need to load some classes which are not in your classpath.

Java Example

Assume folder “c:\\other_classes\\” is not in your project classpath, here’s an example to show how to load a Java class from this folder. The code and comments are self-explanatory.


import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.CodeSource;
import java.security.ProtectionDomain;

public class App{

	public static void main(String[] args) {
		
	try{
	
		File file = new File("c:\\other_classes\\"); 

                //convert the file to URL format
		URL url = file.toURI().toURL(); 
		URL[] urls = new URL[]{url}; 
			
                //load this folder into Class loader
		ClassLoader cl = new URLClassLoader(urls); 

                //load the Address class in 'c:\\other_classes\\'
		Class  cls = cl.loadClass("com.mkyong.io.Address");		
		
                //print the location from where this class was loaded
		ProtectionDomain pDomain = cls.getProtectionDomain(); 
		CodeSource cSource = pDomain.getCodeSource(); 
		URL urlfrom = cSource.getLocation();
		System.out.println(urlfrom.getFile());
	
	}catch(Exception ex){
		ex.printStackTrace();
	}
  }
}

Output


/c:/other_classes/

You will notice this class is loaded from “/c:/other_classes/“, which is not in your project classpath.

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Jun
4 years ago

Hi, can I specify JARs in the path? let say multiple jars dependents on one another? Thanks.

Arpit
5 years ago

The class file should be present as c:\other_classes\Address.class or c:\other_classes\com\mkyong\io\Address

Gaurav
11 years ago

How to use the methods of this class? Would it be possible without using reflection ?