Method to dynamically load java class files

I believe it's a ClassLoader you're after.

I suggest you start by looking at the example below which loads class files that are not on the class path.

// Create a File object on the root of the directory containing the class file
File file = new File("c:\\myclasses\\");

try {
    // Convert File to a URL
    URL url = file.toURI().toURL();          // file:/c:/myclasses/
    URL[] urls = new URL[]{url};

    // Create a new class loader with the directory
    ClassLoader cl = new URLClassLoader(urls);

    // Load in the class; MyClass.class should be located in
    // the directory file:/c:/myclasses/com/mycompany
    Class cls = cl.loadClass("com.mycompany.MyClass");
} catch (MalformedURLException e) {
} catch (ClassNotFoundException e) {
}

If you add a directory to your class path, you can add classes after the application starts and those classes can be loaded as soon as they have been written to the directory.


Class myclass = ClassLoader.getSystemClassLoader().loadClass("package.MyClass");

or

Class myclass  = Class.forName("package.MyClass");

or loading the class from different folder which is not in the classpath:

File f = new File("C:/dir");
URL[] cp = {f.toURI().toURL()};
URLClassLoader urlcl = new URLClassLoader(cp);
Class myclass  = urlcl.loadClass("package.MyClass");

For further usage of the loaded Class you can use Reflection if the loaded Class is not in your classpath and you can not import and cast it. For example if you want to call a static method with the name "main":

Method m = myclass.getMethod("main", String[].class);
String[] args = new String[0];
m.invoke(null, args);  // invoke the method