×
☰ See All Chapters

How to use modules in Java 9 using requires directive

requires in module-info.java is used to specify the dependent modules. If your module has to use other module then all those modules should be declared in module-info.java using requires directive.

Syntax

requires modulename;

Example

module com.java4coding.other {

requires com.java4coding.app;

}

If multiple modules have to be used then all those should be declared in separate requires directive.

module com.java4coding.other {

requires com.java4coding.app;

requires com.java4coding.client;

}

requires transitive

If module A uses module B, module B uses module C, then module A can access module C only if module B has transitive declaration. In the below screenshots you can observe DemoC class from com.java4coding.c module is accessible from com.java4coding.a module only when com.java4coding.b module has requires  transitive declaration of com.java4coding.c module.

java-module-requires-0
 
java-module-requires-1
 

Package name should not be same with any of the packages from imported module. If module A has a package com.java4coding.test then when module B uses module A, module B should not has any package with the name com.java4coding.test.

java-module-requires-2
 

requires static

If you just want use the modules in compile time then by using the requires static directive, we include modules to compile time only. In the below example we used com.java4coding.service for just compile time. In run time only implementation will be used, and it not necessary to use service interface and abstract methods. So we can include com.java4coding.service module to only compile time by using requires static.

module com.java4coding.service.client {

requires static com.java4coding.service;

requires com.java4coding.service.impl;

}


All Chapters
Author