Now that we've seen how to describe a module in Java, we'll see how to load it dynamically in our application.
In Java, all the classes are loaded using several ClassLoader.In this article, we'll develop a loader for our modules and watch the problems that arrive when working with custom ClassLoaders.
Normally, Java use the system ClassLoader to load all the classes of our application. So it contains all the classes of our application and all the classes our application needs to work. But the problem is that we cannot add our modules jar files into classpath because the application doesn't know the modules jar files names.
Moreover, we cannot theoretically add files to the system ClassLoader. I say theoretically because, we can add files using reflection and call to a private method, but i thing it's not a really good practice.
So we've to create a new ClassLoader to load our modules. We'll do that in two phases :
Browse the module files to get the classes of the modules and the URLs of the modules Jar files
Load the modules into our ClassLoader using the URLs of the first phase
We'll do all the loading in a new class ModularLoader. so let's create a create a method that return the list of classes to load :
```java
public class ModuleLoader {
private static List urls = new ArrayList();
private static List getModuleClasses(){
List classes = new ArrayList();
//Get all the modules of the modules folder
File[] files = new File("folder").listFiles(new ModuleFilter());
for(File f : files){
JarFile jarFile = null;
try {
//Open the Jar File
jarFile = new JarFile(f);
//We get the manifest
Manifest manifest = jarFile.getManifest();
//We get the class name from the manifest attributes
classes.add(manifest.getMainAttributes().getValue("Module-Class"));
urls.add(f.toURI().toURL());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(jarFile != null){
try {
jarFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return classes;
}
private static class ModuleFilter implements FileFilter {
@Override
public boolean accept(File file) {
return file.isFile() && file.getName().toLowerCase().endsWith(".jar");
}
}
}
```
Like you see, it's not complicated at all. We search all the module files and then for each jar file, we open it, get the manifest et read the class name of the module. And then, for the second phase, we get the URL to the Jar file.
Of course, this loader is not perfect. We can have modules with no manifest or manifest with no class name and the errors must be correctly treated, but this is not the objective of this post to be perfect.
Now we can do the second phase, adding a method to create the ClassLoader, instantiate the modules and return them :
```java
private static ClassLoader classLoader;
public static List loadModules(){
List modules = new ArrayList();
AccessController.doPrivileged(new PrivilegedAction