Main Tutorials

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.

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Jun
2 years ago

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

Arpit
3 years ago

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

Gaurav
9 years ago

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