Home > Back-end >  How does requires transitive work in Java?
How does requires transitive work in Java?

Time:08-16

Can com.demo.invoice access com.demo.product.service?

module com.demo.product {
    exports com.demo.product.service to com.demo.order;
}
module com.demo.order {
    exports com.demo.order.orderservice;
    requires transitive com.demo.product;
}
module com.demo.invoice {
    requires com.demo.order;
}

CodePudding user response:

How does requires transitive work in Java?

If module A transitively requires module B, then any module which reads module A also reads module B. In other words, the following:

module A {
  requires transitive B;
}

module B {}

module C {
  requires A;
}

Is as if module C defined a requires directive for both A and B. You use requires transitive when a module has types as part of its public API that come from another module.


Can com.demo.invoice access com.demo.product.service?

No, the com.demo.invoice module cannot access types in the com.demo.product.service package, even though said module does in fact read the com.demo.product module. This is because:

exports com.demo.product.service to com.demo.order;

Is a qualified exports directive. Other than the com.demo.product module itself, only the com.demo.order module can access the types in the com.demo.product.service package. If you changed the directive to either:

 // unqualified exports
exports com.demo.product.service;

Or:

// include 'com.demo.invoice' in qualified exports
exports com.demo.product.service to com.demo.order, com.demo.invoice;

Then the answer to this question would change to "yes".

  • Related