Java 9 Modules (Part 3): Directives

In this last post about Java 9 modules, we will take a closer look at some module directives. We will explain what they are and show their usage by means of an example. We will build upon the example used in part 1 and part 2, it is advised to read these posts before continue reading. The sources used in this post are available on GitHub in branch feature/modules-directives.

requires

The requires directive indicates that this module depends on another module. We used this directive in the previous posts, where the module com.mydeveloperplanet.jpmshello depends on module com.mydeveloperplanet.jpmshi.

requires com.mydeveloperplanet.jpmshi;


The requires directive also knows two variants:

exports

The exports directive indicates which public types of the module's package are accessible to other modules. We used this directive in the previous posts where the package com.mydeveloperplanet.jpmshi was made accessible so that module com.mydeveloperplanet.jpmshello was able to use the HiModules class.

exports com.mydeveloperplanet.jpmshi;


Also, an exports...to directive exists. After the to keyword, it is possible to set the list of packages that are allowed to use the exported packages.

opens

The opens directive also indicates which public types of the module's package are accessible to other modules. The difference between that and exports is that opens is not for compile time, only during runtime, while exports is for both compile time and runtime. The opens directive can typically be used when you want to allow other modules to use reflection for the types in the specified packages, but not to use them during compile time. Let's make this more clear by means of an example.

We create a static method checkExportsDirectiveWithReflection in the HelloModules class and invoke it from its main method. We use reflection to invoke the getHi method from the HiModules class, just like we did before by invoking it directly.

private static void checkExportsDirectiveWithReflection() {
    try {
        Class c = Class.forName("com.mydeveloperplanet.jpmshi.HiModules");
        Method m = c.getMethod("getHi");
        System.out.println(m.invoke(c.getDeclaredConstructor().newInstance()));
    } catch (Throwable e) {
        System.err.println(e);
    }
}


Build with Maven and run the example with the following command:

java --module-path com.mydeveloperplanet.jpmshello/target/jpmshello-1.0-SNAPSHOT.jar;com.mydeveloperplanet.jpmshi/target/jpmshi-1.0-SNAPSHOT.jar --module com.mydeveloperplanet.jpmshello/com.mydeveloperplanet.jpmshello.HelloModules


The output is:

Hello Modules!
The XML namespace prefix is: xml
Hi Modules!
Hi Modules!


This is as expected because the package of class HiModules is exported.

Create a new class OpensModules in the package com.mydeveloperplanet.jpmsopens in the module com.mydeveloperplanet.jpmshi. The content is similar to that of the HiModules class:

public class OpensModules {

    public String getHiOpens() {
        return "Hi Opens Directive!";
    }

}


In the class HelloModules, we create the static method checkOpensDirectiveWithReflection and invoke it from the main method, just like we did for the method checkExportsDirectiveWithReflection:

private static void checkOpensDirectiveWithReflection() {
    try {
        Class c = Class.forName("com.mydeveloperplanet.jpmsopens.OpensModules");
        Method m = c.getMethod("getHiOpens");
        System.out.println(m.invoke(c.getDeclaredConstructor().newInstance()));
    } catch (Throwable e) {
        System.err.println(e);
    }
}


Building with Maven and running this example gives the following error:

java.lang.IllegalAccessException: class com.mydeveloperplanet.jpmshello.HelloModules (in module com.mydeveloperplanet.jpmshello) cannot access class com.mydeveloperplanet.jpmsopens.OpensModules (in module com.mydeveloperplanet.jpmshi) because module com.mydeveloperplanet.jpmshi does not export com.mydeveloperplanet.jpmsopens to module com.mydeveloperplanet.jpmshello


This may not suprise us because we did not export the package in the module-info of the module com.mydeveloperplanet.jpmshi. The build was successful because we did not explicitly use class OpenModules. We only used it within our reflection code and thus the compiler had no information that the class was being used during runtime.

We add the following to the module-info of the module com.mydeveloperplanet.jpmshi:

opens com.mydeveloperplanet.jpmsopens;


Then, build with Maven and run the example again. The output is:

Hello Modules!
The XML namespace prefix is: xml
Hi Modules!
Hi Modules!
Hi Opens Directive!


Now that we've added the open directive to the module-info, it is allowed to use the class during runtime.

It is also possible to set the open directive in front of the module. This way, all public types within the module can be used during runtime. The module-info of module com.mydeveloperplanet.jpmshi becomes the following:

open module com.mydeveloperplanet.jpmshi {
    exports com.mydeveloperplanet.jpmshi;
}


Just like the exports directive, an opens...with directive exists in order to limit the accessibility to a set of packages.

provides...with

The provides...with directive indicates that a module provides a service implementation. The module is, therefore, a service provider. After the provides part, the interface or abstract class is listed. After the with part, the implementation class is listed.

Before continuing, it is probably a good thing to revisit the concept of services. I can recommend the following articles:

Create the Service Provider Interface

We will first create the Service Provider Interface by means of the following steps:

The ServiceProviderInterface is defined as follows:

package com.mydeveloperplanet.serviceproviderinterface.spi;

public interface ServiceProviderInterface {

  void printServiceName();

}


Create the Service

Create the class Service in the package com.mydeveloperplanet.serviceproviderinterface. We create the service as a singleton and provide it with one method printServiceNames. This method loads the service implementation and invokes the method printServiceName of all found services.

The class Service is defined as follows:

package com.mydeveloperplanet.serviceproviderinterface;

import com.mydeveloperplanet.serviceproviderinterface.spi.ServiceProviderInterface;

import java.util.ServiceLoader;

public class Service {
    private static Service ourInstance = new Service();

    public static Service getInstance() {
        return ourInstance;
    }

    private Service() {}

    public void printServiceNames() {
        ServiceLoader < ServiceProviderInterface > serviceLoader = ServiceLoader.load(ServiceProviderInterface.class);
        services.iterator().forEachRemaining(service - > service.printServiceName());
    }
}


Create a Service Provider

Now it is time to create a Service Provider, which implements the Service Provider Interface. We create a new module named com.mydeveloperplanet.serviceprovider1, which contains a module-info file and the package com.mydeveloperplanet.serviceprovider1 with the class ServiceProvider1.

Before we are able to do this, we need to adapt the module-info of the module com.mydeveloperplanet.serviceproviderinterface in order to export the package that contains the ServiceProviderInterface:

module com.mydeveloperplanet.serviceproviderinterface {
    exports com.mydeveloperplanet.serviceproviderinterface.spi;
}


And, we need to add the module com.mydeveloperplanet.serviceproviderinterface to the module-info of our module com.mydeveloperplanet.serviceprovider1:

module com.mydeveloperplanet.serviceprovider1 {
    requires com.mydeveloperplanet.serviceproviderinterface;
}


We also need to add the module com.mydeveloperplanet.serviceproviderinterface as a Maven dependency to the POM of the module com.mydeveloperplanet.serviceprovider1:

<dependencies>
    <dependency>
        <groupId>com.mydeveloperplanet</groupId>
        <artifactId>ServiceProviderInterface</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
</dependencies>


Class ServiceProvider1 implements our interface ServiceProviderInterface and is defined as follows:

package com.mydeveloperplanet.serviceprovider1;

import com.mydeveloperplanet.serviceproviderinterface.spi.ServiceProviderInterface;

public class ServiceProvider1 implements ServiceProviderInterface {
    @Override
    public void printServiceName() {
        System.out.println("This is Service Provider 1");
    }
}


Create a Client

We are almost there. We need to create a client that will use the created service. We will extend the HelloModules with a checkProvidesWith method. But first, we need to add the module com.mydeveloperplanet.serviceproviderinterface as a Maven dependency to the POM of module com.mydeveloperplanet.jpmshello and extend the module-info of module com.mydeveloperplanet.jpmshello.

<dependency>
    <groupId>com.mydeveloperplanet</groupId>
    <artifactId>ServiceProviderInterface</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
module com.mydeveloperplanet.jpmshello {
    requires java.xml;
    requires com.mydeveloperplanet.jpmshi;
    requires com.mydeveloperplanet.serviceproviderinterface;
}


We will need the class Service from module com.mydeveloperplanet.serviceproviderinterface, therefore, we also have to export the package com.mydeveloperplanet.serviceproviderinterface of module com.mydeveloperplanet.serviceproviderinterface.

module com.mydeveloperplanet.serviceproviderinterface {
    exports com.mydeveloperplanet.serviceproviderinterface.spi;
    exports com.mydeveloperplanet.serviceproviderinterface;
}


The method checkProvidesWith invokes the method printServiceNames of our Service:

private static void checkProvidesWith() {
    Service service = Service.getInstance();
    service.printServiceNames();
}


Build and Run

Build and run the example:

java --module-path com.mydeveloperplanet.jpmshello/target/jpmshello-1.0-SNAPSHOT.jar;com.mydeveloperplanet.jpmshi/target/jpmshi-1.0-SNAPSHOT.jar;com.mydeveloperplanet.serviceproviderinterface/target/serviceproviderinterface-1.0-SNAPSHOT.jar;com.mydeveloperplanet.serviceprovider1/target/serviceprovider1-1.0-SNAPSHOT.jar --module com.mydeveloperplanet.jpmshello/com.mydeveloperplanet.jpmshello.HelloModules


The following error occurs:

Exception in thread "main" java.util.ServiceConfigurationError: com.mydeveloperplanet.serviceproviderinterface.spi.ServiceProviderInterface: module com.mydeveloperplanet.serviceproviderinterface does
 not declare `uses`
 at java.base/java.util.ServiceLoader.fail(ServiceLoader.java:588)
 at java.base/java.util.ServiceLoader.checkCaller(ServiceLoader.java:574)
 at java.base/java.util.ServiceLoader.<init>(ServiceLoader.java:503)
 at java.base/java.util.ServiceLoader.load(ServiceLoader.java:1684)
 at com.mydeveloperplanet.serviceproviderinterface/com.mydeveloperplanet.serviceproviderinterface.Service.printServiceNames(Service.java:25)
 at com.mydeveloperplanet.jpmshello/com.mydeveloperplanet.jpmshello.HelloModules.checkProvidesWith(HelloModules.java:48)
 at com.mydeveloperplanet.jpmshello/com.mydeveloperplanet.jpmshello.HelloModules.main(HelloModules.java:21)


Add the provides...with directive to the module-info.java of com.mydeveloperplanet.serviceprovider1. After provides, we add the interface. After with, we add the implementation:

module com.mydeveloperplanet.serviceprovider1 {
    requires com.mydeveloperplanet.serviceproviderinterface;

    provides com.mydeveloperplanet.serviceproviderinterface.spi.ServiceProviderInterface with com.mydeveloperplanet.serviceprovider1.ServiceProvider1;
}


Add the uses directive to the module-info of com.mydeveloperplanet.serviceproviderinterface. After uses, we add the interface:

module com.mydeveloperplanet.serviceproviderinterface {
    exports com.mydeveloperplanet.serviceproviderinterface.spi;
    exports com.mydeveloperplanet.serviceproviderinterface;

    uses com.mydeveloperplanet.serviceproviderinterface.spi.ServiceProviderInterface;
}


Build and run the example. The output is as follows:

Hello Modules!
The XML namespace prefix is: xml
Hi Modules!
Hi Modules!
Hi Opens Directive!
This is Service Provider 1


This is the expected output.

Add the Second Service Provider

To conclude with, we add a second Service Provider, ServiceProvider2, that isidentical to ServiceProvider1. The only thing we will change is to make the module-info.java of ServiceProvider2 a bit more readable by using import statements. Before, we had:

module com.mydeveloperplanet.serviceprovider2 {
    requires com.mydeveloperplanet.serviceproviderinterface;

    provides com.mydeveloperplanet.serviceproviderinterface.spi.ServiceProviderInterface with com.mydeveloperplanet.serviceprovider2.ServiceProvider2;
}


It is possible to use import statements, just like in a normal Java class:

import com.mydeveloperplanet.serviceprovider2.ServiceProvider2;
import com.mydeveloperplanet.serviceproviderinterface.spi.ServiceProviderInterface;

module com.mydeveloperplanet.serviceprovider2 {
    requires com.mydeveloperplanet.serviceproviderinterface;

    provides ServiceProviderInterface with ServiceProvider2;
}


Run and build the example:

java --module-path com.mydeveloperplanet.jpmshello/target/jpmshello-1.0-SNAPSHOT.jar;com.mydeveloperplanet.jpmshi/target/jpmshi-1.0-SNAPSHOT.jar;com.mydeveloperplanet.serviceproviderinterface/target/serviceproviderinterface-1.0-SNAPSHOT.jar;com.mydeveloperplanet.serviceprovider1/target/serviceprovider1-1.0-SNAPSHOT.jar;com.mydeveloperplanet.serviceprovider2/target/serviceprovider2-1.0-SNAPSHOT.jar --module com.mydeveloperplanet.jpmshello/com.mydeveloperplanet.jpmshello.HelloModules


The output now also prints This is Service Provider 2:

Hello Modules!
The XML namespace prefix is: xml
Hi Modules!
Hi Modules!
Hi Opens Directive!
This is Service Provider 2
This is Service Provider 1

Summary

In this post, module directives were explained and used in several examples. This concludes this series of Java 9 modules. I hope you enjoyed this series and start using Java 9 Modules!

 

 

 

 

Top