Java 9 Modules - Compilation Modes and Project Structure

[Last Updated: Sep 5, 2018]

In Java 9, the compiler operates in one of the three modes (specified in JEP-261):

Legacy Mode

This mode operates as defined by Java 8 specification (or before), where we use traditional options (class path etc) rather than any of the modules related options (like --module-path). This mode still works in Java 9 and is referred as Legacy mode. In this mode, our code runs as the Unnamed Module during runtime.

Single Module Mode

In this mode, the code is structured in a traditional package-hierarchical directory tree. Our code has and runs on module-path rather than on class path. In this structure, we place our directly under src directory. There cannot exist multiple in the same directory tree, that's why it is called single-module mode.

Following is a typical single-module directory structure:

D:\single-module-mode-example>"tree /A /F"

To compile it:

D:\single-module-mode-example> javac -d myOutputDir src\com\logicbig\ src\

If our code requires other modules then we need to use --module-path option:

D:\single-module-mode-example> javac -d myOutputDir --module-path moduleFolder src\com\logicbig\ src\

Where moduleFolder contains compiled code or jar of other modules. The other module can be an automatic module as well.

To run our single module (assuming MyClass has the main method):

D:\single-module-mode-example> java --module-path modFolder --module

We have been using the single-module mode in our most of the previous tutorials including the getting started example.

Multi Module Mode

In this mode, we can place multiple modules under the same source directory. During compile time this main source directory should be specified with --module-source-path option. The source tree for each individual module are placed in its own subdirectory under the main source directory.

Following is a typical multiple-module directory structure:

D:\multi-module-mode-example>"tree /A /F"
| |
| |
| \---data

To compile it:

D:\multi-module-mode-example> javac -d myOutputDir --module-source-path src src\\example\one\ src\\ src\module.two\example\two\ src\module.two\


 javac -d <the-output-folder> --module-source-path <multi-module-main-src-folder> <path-to-each-java-file>

if we try to run without --module-source-path (like we do with single-module mode):

D:\multi-module-mode-example> javac -d myOutputDir src\\example\one\ src\\ src\module.two\example\two\ src\module.two\
src\\ error: too many module declarations found
module {
1 error

To run it (given that AppMain has the main class):

D:\multi-module-mode-example>java --module-path myOutputDir --module

See Also