📜 ⬆️ ⬇️

Java 6. Using ServiceLoader to build a modular application

Something I recently became lazy. I used to follow all updates in Java. At the time, Java 1.5 Tiger, I just "eaten with giblets," but, alas, everything was already forgotten.

And somehow, the release of Java 1.6 Mustang went completely unnoticed for me. I will not describe all the “buns” in this article, but will only tell about ServiceLoader.

The simplest example of using a ServiceLoader is developing a modular application. If I did not know about the existence of this class, then I would most likely use some kind of RCP , for example Eclipse RPC or NetBeans RPC . But quite often there is already a written application to which you want to fasten the possibility of using plug-ins. And I want to do it simply, elegantly, without "extra blood."

Modular Hello World.


Formulation of the problem

So, we will do the modular "Hello World". It is the responsibility of the module to provide a line that will be output to the console using the main program.
')
API module

Create a jar file with the API of our module and put one single file demo.HelloWorldInterface.java with the following content:
package demo;
public interface HelloWorldInterface {
public String getMessage();
}


* This source code was highlighted with Source Code Highlighter .

We have described the interface that will be used in the main program and which we will now embed by our plugin.

Plugin

Create a jar file with the implementation of our API and first put in it the demo.HelloWorldImpl.java file with the following content:
package demo;
public class HelloWorldImpl implements HelloWorldInterface {
public String getMessage() {
return "Hello World" ;
}
}


* This source code was highlighted with Source Code Highlighter .

And then we'll put the demo.HelloWorldInterface file in the META-INF / services directory, which contains only one line
demo.HelloWorldImpl

Main program

And now we are implementing our main program. The demo.Main class code that contains the main method looks like this
package demo;
import java.util.ServiceLoader;
public class Main {
public static void main( String [] args) {
for (HelloWorldInterface hw : ServiceLoader.load(HelloWorldInterface. class )) {
System. out .println(hw.getMessage());
}
}
}


* This source code was highlighted with Source Code Highlighter .

Launch

And now start the Main class with the indication in the class path of our two previously prepared jar'ok. Voila Modular application is ready. All the magic lies in the ServiceLoader.load () method, which, when called, searches all the loaded jars in the META-INF / services directory of the files with the name of the transferred interface (in this case, demo.HelloWorldInterface) and reads the names of classes implement this interface. After that, instances of these classes are created and returned by this method.

Sources

Source: https://habr.com/ru/post/56165/


All Articles