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.

3 comments on “How to load classes which are not in your classpath

Leave a Comment

Your email address will not be published. Required fields are marked *