Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 3rd party library in Java9 module?

Tags:

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?

like image 664
igr Avatar asked Oct 12 '17 15:10

igr


People also ask

Can a jar contain multiple modules?

Each module-info. java which lives in the default package will be compiled to module-info. class . Therefore, one JAR cannot contain multiple modules.

Do you have to use modules in Java?

No. There is no need to switch to modules. There has never been a need to switch to modules. Java 9 and later releases support traditional JAR files on the traditional class path, via the concept of the unnamed module, and will likely do so until the heat death of the universe.


2 Answers

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; } 
like image 77
ZhekaKozlov Avatar answered Oct 03 '22 22:10

ZhekaKozlov


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.

like image 45
Naman Avatar answered Oct 04 '22 00:10

Naman