meriton meriton - 2 months ago 15
Java Question

Does the Java 9 Module system support optional dependencies?

Background

In maven, an artifact can declare a dependency with

<optional>true</optional>


which means that the dependency is not required, but can be used if present.

The State of the Module System seems to specify that a module can only read modules it has required.

Questions


  • Does the Java 9 module system indeed not support optional dependencies?

  • Why not?

  • What alternatives to optional dependencies does the Java 9 module system provide?



Use Case

I have a framework that integrates various libraries that may or may not be used by an application. Currently, this framework is a single JAR that reflects upon the classpath to skip integration code for absent libraries.

I guess we could split this into a separate module for each configuration, but this would cause a combinatorial explosion in the number of JARs, because we'd not only need a separate JAR for each optional dependency, but also a separate JAR for most pairs of optional dependencies ...

Answer

There is currently a proposal for that exact use case:

Extend the language of module declarations to allow the static modifier to be used on a requires directive, with the following meanings:

  • At compile time, requires static M expresses a mandatory dependence. It is an error if a suitable module cannot be found amongst the observable modules and resolved.

  • In phases after compile time, requires static M expresses an optional dependence. The module system will not search the observable modules for a suitable module during resolution, but if the resulting module graph contains a suitable module then it will add the appropriate readability edge prior to doing the usual post-resolution sanity checks. [...]

Thus a hypothetical module declaration of the form

module joda.beans {
    requires static joda.collect;
    ...
}

would ensure that the joda.collect module is available at compile time, so that code in the joda.beans module that refers to joda.collect can be compiled without any fuss. It would not, however, guarantee that joda.collect is available at link time or run time.