Develop a modular application – Implementation
Now that we saw in details the characteristics of the modules, we'll see how to implement a module.
We need a simple container for our module to load it after with a loader from the modular application.
In this post, we'll only see what will be a module in Java, we'll the loading of the modules in the next (and last) post.
A module is completely independent of the module, so we cannot include it directly in the application. We must distinguish the file of the module and the file of the application.
So what will be these files ? Because we're in Java, we use Jar files. So the modules will be Jar files extending the applications.
And now in Java, a module will be an interface describing the main characteristics of the module. We'll be simple for the moment. A module must be pluggable to the application and unpluggable. Moreover the module has also a name and we can get this name. At this moment, this is all we need :
We must have a simple interface to describe a module :
public interface IModule { public void plug(); public void unplug(); public String getName(); }
With that interface, we can create the most simple module that only prints to the console :
package org.modules.simple; public class SimpleModule implements IModule { @Override public void plug(){ System.out.println("Hello kernel !"); } @Override public void unplug(){ System.out.println("Bye kernel !"); } @Override public String getName(){ return "Simple module"; } }
So we'll create a Jar file containing our class. We need a solution for the application to know which class to launch. So we need write this somewhere.
A naïve solution is to browse the Jar file and test each class if it implements the interface. This method works but is not optimal but that can be really inefficient in large Jar file. So we'll use the tools offered by Java and add an information in the Jar manifest to indicate to the application which class must be loaded.
So here it's the manifest for our example :
Manifest-Version: 1.0 Module-Class: org.modules.simple.SimpleModule
With that the module loader will know which class it must instantiate to create a module. An other solution is to use the ServiceLoader of Java 6.
In the next post, we'll see how to load our module and we'll test an application with two simples modules.
Comments
Comments powered by Disqus