How to use 3rd party library in Java9 module?

igr picture igr · Oct 12, 2017 · Viewed 7.2k times · Source

I have some java9 module that uses 3rd party library that is not Java9 module, just a simple utility jar.

However, the compiler complains that it can't find a package from my utility.

What should I do in module-info.java to enable usage of my 3rd party library?

Answer

ZhekaKozlov picture ZhekaKozlov · Oct 12, 2017

You can use your library as an automatic module. An automatic module is a module that doesn't have a module descriptor (i.e. module-info.class).

But what name do you need to specify to refer to an automatic module? The name of the automatic module is derived from the JAR name (unless this JAR contains an Automatic-Module-Name attribute). The full rule is quite long (see Javadoc for ModuleFinder.of), so for simplicity, you just have to drop the version from its name and then replace all non-alphanumeric characters with dots (.).

For example, if you want to use foo-bar-1.2.3-SNAPSHOT.jar, you need to add the following line to module-info.java:

module <name> {
    requires foo.bar;
}