Java 9 Modules directives (part 3)

In this last post about Java 9 modules we will take a closer look at some of the modules directives. We will explain what they mean and show the 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:

  • requires transitive <module name>: this means that any module that reads your module, implicitly also reads the transitive module. E.g. if your module contains a method which is public available and returns a type of another module. When transitive is not used, any module reading your module, would explicitly have to add the dependent module.
  • requires static <module name>: this is an optional dependency. The module is needed at compile time, but not at run time.

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 in order 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 which 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 with exports is that opens is not during compile time but only during run time, while exports is during compile time and during run time. 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 the 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 package com.mydeveloperplanet.jpmsopens in module com.mydeveloperplanet.jpmshi. The contents is similar to that of the HiModules class:

public class OpensModules {

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

}

In 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);
  }
}

Build with Maven and run 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 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 run time.

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

opens com.mydeveloperplanet.jpmsopens;

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 added the open directive to the module-info, it is allowed to use the class during run time.

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 run time. 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 continue reading this paragraph, it is a good thing to revise the concept of services. I can recommend the following articles:

Create the Service Provider Interface

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

  • We create a new Module com.mydeveloperplanet.serviceproviderinterface.
  • In the src – main – java directory, we create our module-info.java file.
  • Inside our source directory, we create the package com.mydeveloperplanet.serviceproviderinterface.spi
  • Finally, we create the interface ServiceProviderInterface which defines one method printServiceName to be implemented

The ServiceProviderInterface is defined as follows:

package com.mydeveloperplanet.serviceproviderinterface.spi;

public interface ServiceProviderInterface {

  void printServiceName();

}

Create the Service

Create the class Service into package com.mydeveloperplanet.serviceproviderinterface. We create the service as a singleton and provide it with one method printServiceNames. This method loads the service implementations 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 package com.mydeveloperplanet.serviceprovider1 with class ServiceProvider1.

Before we are able to do this, we need to adapt the module-info of module com.mydeveloperplanet.serviceproviderinterface in order to export the package which 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 module com.mydeveloperplanet.serviceproviderinterface as a Maven dependency to the pom of 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 which will use the created service. We will extend the HelloModules with a checkProvidesWith method. But first, we need to add 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 to module-info.java of com.mydeveloperplanet.serviceprovider1 the provides…with directive. 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 to module-info of com.mydeveloperplanet.serviceproviderinterface the uses directive. 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 output as expected.

Add second Service Provider

To conclude with, we add a second Service Provider ServiceProvider2 identical 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 the 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!

2 thoughts on “Java 9 Modules directives (part 3)”

  1. good stuff, though I’m left with a question. I’m writing “Spring” (or any framework that does classpath scanning for classes annotated with annotation, JPA/CDI, etc). How does my framework read my later developed library? is this the service provider stuff? could you show an example of this?

    Like

    1. For my next post, I created a small Spring Boot application with one RestController. I only had to add Spring modules into my module-info. I did not have to ‘export’ or ‘open’ anything in this case. Spring does use reflection in some cases. When you encounter an IllegalAccessException, you will need to use the ‘opens’ directive as described above: Spring is not allowed to use your classes during compile time, but is allowed to use them during runtime (for those that are marked with the ‘opens’ directive).
      You only need to use the service provider stuff if you are going to use the Java Services. When you are using Spring, you do not need to use this.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.