How to Declare Modules in java 9

2.3k views Asked by At

I want to use java 9 modules in my project. I want to put my data and service classes (in package named com.test.base) in one module named (Base), and put other things like main class and GUI (in package named com.test.main) in another module named (Main).

  • How to declare simple module (Base)?
  • How to declare module (Main) with dependency of (Base) module?
  • I also want to use (Base) module with reflection.

  • Assume my root package is com.test so what directory structure should I use for these modules?

1

There are 1 answers

2
Naman On

The jigsaw quick-start is a nice place to start off with this to help you out. To answer the specific questions:

How to declare simple module (Base)?

Create a class named module-info.java within com.test.base directory with the definition as:

module base {
     exports com.test.base;
}

This exports the com.test.base package.


How to declare module (Main) with dependency of (Base) module?

Same as the other module base a class named module-info.java within com.test.main directory with the definition as:

module main {
    requires base;
}

Makes use of the exported package.


I also want to use (Base) module with reflection.

Depending on yoru usage, if the API os removed or changes as listed here, then you can use the --add-exports java option as detailed in the JEP-261

I would also suggest reading Nicolai's answer to How to solve InaccessibleObjectException ("Unable to make {member} accessible: module {A} does not 'opens {package}' to {B}") on Java 9? for a nice explanation over how to make use of reflection in Java-9.

the correct fix is to launch the JVM as follows:

--add-opens has the following syntax: {A}/{package}={B} 
java --add-opens java.base/java.lang=ALL-UNNAMED 

If the reflecting code is in a named module, ALL-UNNAMED can be replaced by its name.


Assume my root package is com.test so what directory structure should I use for these modules?

Your directory structure should be somewhat like:

src/main/java
 - com.test
   - base
     - module-info.java
     - com/test/base/Main.java
   - main
     - module-info.java
     - com/test/main/SimpleClass.java