Search code examples
javajava-9java-platform-module-system

Resolve optional dependencies in Java 9 Module System


Java 9 module system support optional dependencies through requires static my.module. The dependency is only used at compile-time, and it won't be resolved at run-time even if it is in the module-path. So, how could optional dependencies be resolved?

  1. A solution: Add flag --add-modules my.module. Question: is the dependency added to the root dependency or is it added as root?
  2. Is it possible to have a direct requires to avoid using add-modules flag?

Solution

  • A solution: Add flag --add-modules my.module. Question: is the dependency added to the root dependency or is it added as root?

    The module added using the flag --add-modules is added to the default set of root modules and the module graph and resolved at runtime for execution since the dependency on the module was defined to be optional during the compile time.

    Is it possible to have a direct requires to avoid using add-modules flag?

    Yes, you can have a direct requires as well for such dependencies and make sure module is added to the module graph non-optionally, but that is a matter of design when you consider optional vs non-optional dependencies for your project.

    The requires static basically provides a means to specify a module dependence that is mandatory at compile time but optional at runtime, for use with libraries that are not strictly necessary but can be leveraged if present at runtime.