How to use 3rd party library in Java9 module?

不羁的心 提交于 2019-11-27 08:26:05

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 should you use to refer to this 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;
}

Just to put 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-info.java, declare a requires to that module name as:-

    module your.module {
        requires log4j.api;
    }
    

    That's it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!