Course contentsShow
← Java
Lesson 2478 of 2,87047. Java Platform Module System (JPMS)Free lesson

Combining requires Modifiers

Explore using requires transitive static together and understand when this combination is appropriate.

Combining requires Modifiers

What you'll learn: How to use requires static and requires transitive together, and when this combination makes sense.


The Core Idea

You've learned about requires transitive (which passes on dependencies to modules that depend on you) and requires static (which makes a dependency optional at runtime). Java allows you to combine both modifiers in a single directive: requires transitive static.

This combination means:

  • The dependency is transitive — modules reading your module automatically read this dependency too
  • The dependency is optional at runtime — the module isn't required to be present when your module runs

When Is This Appropriate?

This combination is rare but useful when you're building a framework or library that exposes types from an optional dependency in its API.

Example Scenario

Imagine you're building a logging facade module. You want to support SLF4J types in your API, but you don't want to force all users to have SLF4J at runtime (they might use a different logging implementation):

module my.logging.facade {
    requires transitive static org.slf4j;
    exports com.mycompany.logging;
}

Your module's exported API might reference SLF4J's Logger interface. With requires transitive, any module that reads my.logging.facade can also access SLF4J types. With static, SLF4J doesn't need to be present at runtime unless someone actually uses those SLF4J-specific features.

The Trade-off

This combination provides flexibility but adds complexity. Users of your module must understand that certain features require the optional dependency to be present. Use this pattern sparingly and document it clearly.

Key Takeaway: requires transitive static combines transitivity with optionality — useful for exposing types from optional dependencies in your API, but rare and requiring careful documentation.