| Start |
|---|
| Using URLClassLoader There are several ways to implement a plugin system for a Java application. One of the simplest is to use URLClassLoader. The following example will involve a bit of JavaFX code. Suppose we have a module of a main application. This module is supposed to load plugins in form of Jars from 'plugins' folder. Initial code: Then, we create an interface which will represent a plugin. We want to load classes which implement this interface, so first we need to filter files which have a '.jar' extension: If there are any files, we need to create collections of URLs and class names: Let's add a static HashSet to MainApplication which will hold loaded plugins: Next, we instantiate a URLClassLoader, and iterate over class names, instantiating classes which implement Plugin interface: Then, we can call plugin's methods, for example, to initialize them: The final code of MainApplication: Let's create two plugins. Obviously, the plugin's source should be in a separate module. Second plugin: These plugins have to be packaged into standard Jars - this process depends on your IDE or other tools. When Jars will be put into 'plugins' directly, MainApplication will detect them and instantiate appropriate classes. RemarksIf you use an IDE and/or build system, it is much easier to set up this kind of project. You create a main application module, then API module, then create a plugin module and make it dependent on the API module or both. Next, you configure where the project artifacts are to be put - in our case the compiled plugin jars can be sent straight to 'plugins' directory, thus avoiding doing manual movement. |
Read Article
https://develop.horje.com/learn/1434/reference