Static Dependencies: requires static
What You'll Learn
You'll learn how to declare optional, compile-time-only module dependencies that aren't required when your application runs.
What Is requires static?
The requires static directive tells the module system: "I need this module to compile my code, but it's optional at runtime." This is perfect for dependencies that provide compile-time annotations, code generation, or optional features that users might not always need.
Think of it like a cookbook that references specialty tools. You need to know about them to write the recipes (compile), but readers (runtime users) don't need to own those tools unless they actually make those specific dishes.
Basic Syntax
module com.example.myapp {
requires static lombok; // Optional at compile-time
}
If lombok isn't present at runtime, the JVM won't complain—as long as you don't actually try to use it.
When to Use requires static
1. Annotation Processing Libraries
Tools like Lombok or AutoValue generate code at compile-time but aren't needed afterward:
module com.example.domain {
requires static lombok;
exports com.example.domain;
}
2. Optional Framework Integrations
If your library can work with Spring but doesn't require it:
module com.example.plugin {
requires static spring.context; // Only needed if user enables Spring
}
3. Tooling and Development Dependencies
Code analysis tools or testing annotations that shouldn't bloat production runtimes.
How It Differs from Regular requires
requires: Must be present at both compile-time and runtimerequires static: Must be present at compile-time, optional at runtime
If code tries to use a requires static module that's missing at runtime, you'll get a ClassNotFoundException or NoClassDefFoundError—but only when that code path executes.
Key Takeaway: Use requires static for optional dependencies needed during compilation but not essential at runtime—perfect for annotation processors, optional integrations, and development-only tools.