Search code examples
javajavacjava-modulejava-platform-module-system

How to compile with `javac` modules with `exports... to` directives without any warnings?


I've got three modules - a main one and two dependencies. All the modules are in the same folder level and are organised in folders ./main, ./first and ./second, correspondingly.

The second module has only one class:

package characterz;

public class Freaker {

    public void freakOut() {
        System.err.println("ARGH!!!#$%@");
    }
}

... and its' module-info.java file is:

module second {
    exports characterz;
}

The first module has only one class:

package characters;

public class Captain {

    public void payRespects() {
        System.out.println("Presses \"F\" ...");
    }

}

... and its' module-info.java file is:

module first {
    exports characters;
    requires transitive second;
}

The main module has only one class:

package app;

import characters.Captain;
import characterz.Freaker;

public class Main {
    public static void main(String... argz) {
        Captain cap = new Captain();
        Freaker freak = new Freaker();
        cap.payRespects();
        freak.freakOut();
    }
}

... and its' module-info.java file is:

module main {
    requires first;
}

In order to compile these three modules, I perform the following sequence of commands:

javac -d modules/second $(find second -name *.java)

javac -p modules/second -d modules/first $(find first -name *.java)

javac -p modules/second:modules/first -d modules/main main/app/Main.java main/module-info.java

... and it compiles fine. To make sure everything is OK we may run our program this way: java -p modules -m main/app.Main

But if I try to use exports... to directive in the first module:

module first {
    exports characters to main;
    requires transitive second;
}

... then compilation process starts giving me a warning at compilation of the first module with this message:

first/module-info.java:2: warning: [module] module not found: main
    exports characters to main;
                          ^
1 warning

It still compiles, though. Nevertheless, how one may avoid getting these warnings when compiling modules with exports... to directives?


Solution

  • Let's assume you have organized your project like this:

    .           // current working directoy
    |-- src     // source code
    |  |-- first
    |  |-- second
    |  |-- main
    |-- modules // compiled stuff
       |-- first
       |-- second
       |-- main
    

    Then you can compile all modules with

    javac -d modules --module first,second,main --module-source-path src
    

    from the current working directory.
    No need to jump through several hoops there.