How to load classes which are not in your classpath
Written on January 14, 2010 at 4:36 pm by
mkyong
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.
This article was posted in Java category.
All Java Tutorials
- Java Core Technology - Java RegEx, Java XML, Java I/O, Java Misc
- J2EE Frameworks - Hibernate, Spring 2.5, Spring MVC, Struts 1.x, Struts 2.x
- Build Tools - Maven, Archiva
- Unit Test - jUnit, TestNG
- Client Scripts - jQuery