Learnitweb

requires transitive in java

1. Introduction

In this tutorial, we’ll discuss the requires transitive. Before starting the discussion, let us discuss what is transitive dependency.

Suppose there are three entities, A, B and C such that the following statements are correct:

  1. A -> B represents a direct dependency relationship and such relationship exists.
  2. There is no direct dependency relationship B -> A.
  3. B -> C represents a direct dependency relationship and such relationship exists.

Then the functional dependency A -> C represents a transitive dependency.

By default a transitive accessibility is not possible in Java 9 module. It means, if moduleA requires moduleB, moduleB requires moduleC then it does not imply that moduleA requires moduleC.

Such transitive accessibility can be achieved using requires transitive.

2. Need of ‘requires transitive’

Suppose there are three modules moduleA, moduleB and moduleC. Their dependencies are like the following:

module moduleA {
	requires moduleB;
}

module moduleB {
	requires moduleC;
}

module moduleC {
	exports pack1;
}

These three module descriptors does not imply that moduleA requires moduleC and moduleA can access pack1. In this case, moduleB is available only to moduleA. The pack1 of moduleC is available only to moduleB.

If moduleA requires moduleC to be available then moduleA needs to do this explicitly.

module moduleA {
	requires moduleB;
	requires moduleC;
}

To solve this issue, moduleB can use requires transitive:

module moduleB {
	requires transitive moduleC;
}

Let us see another example.

Let us understand this with the help of an example.

module foo {
    requires requireModule;
    requires transitive transitiveModule;
}
  • Any module that depends upon the module foo will automatically read the transitiveModule module.
  • On the other hand to access the module requireModule, we must specify a requires clause again.

3. Conclusion

As you continue to explore Java modularization, remember to leverage requires transitive judiciously, considering its implications on your project’s architecture and design. With practice and experimentation, you’ll master this powerful feature, enabling you to build robust and scalable Java applications.