21

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?

ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
igr
  • 10,199
  • 13
  • 65
  • 111

2 Answers2

27

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;
}
ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
  • 3
    Thank you! The funny part is that I did that, but my IntelliJ was still complaining. After I restarted the IDEA there are no more issues. Thanx! – igr Oct 12 '17 at 16:14
  • In some cases no module descriptor can be derived. Is there a way to define an alias to override the invalid automatic name without changing the 3thparty library? Also see https://stackoverflow.com/questions/46501388/unable-to-derive-module-descriptor-for-auto-generated-module-names-in-java-9 – Stefan Dec 12 '17 at 15:26
  • @Stefan Changing jar name is not an option? – ZhekaKozlov Dec 12 '17 at 18:10
  • Not really because there are many jar files I depend on and I want to be able to get updates. Since there is no way to define an alias or a fallback jar for failing automatic module names in module-info.java ... I decided to wait for a new version of the 3thparty libraries (Eclipse plugins) including proper module definitions. Also see https://stackoverflow.com/questions/47773079/how-to-add-org-eclipse-swt-and-other-plugin-dependencies-as-an-automatic-java9 – Stefan Dec 13 '17 at 09:06
14

To put it in simple steps, to use a 3rd party jar (e.g. log4j-api-2.9.1.jar below) in your module:-

  1. Execute the descriptor command of jar tool

     jar --file=/path/to/your/jar/log4j-api-2.9.1.jar --describe-module
    

    This would provide you an output similar to

    No module descriptor found. Derived automatic module. log4j.api@2.9.1 automatic

  2. In your module descriptor file, declare a requires to that module name as:-

     module your.module {
         requires log4j.api;
     }
    

That's it.

Naman
  • 27,789
  • 26
  • 218
  • 353