Java 9模块化编程中requires static可选依赖执行报错原因咨询
Let's break down what's happening here and how to fix it:
The Core Issue: What requires static Actually Does
You changed myModuleA's module declaration to requires static myModuleB—this tells the Java module system that myModuleB is only needed at compile time, not at runtime.
Here's the play-by-play:
- Compile time: The compiler knows it needs
myModuleBto buildmyModuleA(since your code directly referencesM2), so compilation succeeds without issues. - Runtime: The JVM doesn't automatically load
myModuleBbecauserequires staticmarks it as optional. Even though you've included it in the module path, the JVM won't bother resolving it unless explicitly told to—until your code tries to callM2.print(), at which point it can't find the class and throws the error.
Fixes to Try
Depending on whether myModuleB is actually optional for your app, pick one of these solutions:
1. Force the JVM to load myModuleB at runtime
If you want to keep using requires static (maybe for a scenario where myModuleB is optional in some cases), add the --add-modules flag to your run command to explicitly load the module:
gyan@#ns:~/Desktop$ java --module-path out/:OtherModule/ --add-modules myModuleB -m myModuleA/myPack1.M1
This tells the JVM to load myModuleB regardless of the static dependency, so your code will find M2 without issues.
2. Revert to a regular requires dependency
If myModuleB is a mandatory part of your app (which it seems like, since you're calling its methods directly), change your module-info.java back to a standard requires statement:
module myModuleA { requires myModuleB; }
With this, the JVM will automatically load myModuleB at runtime as a required dependency, no extra flags needed.
When Should You Use requires static?
requires static is meant for optional dependencies where your code can run without the module. For example, if you had conditional logic that only uses M2 if it's available:
public class M1 { public static void main(String[] args) { System.out.println("I am M1"); try { // Use reflection to check if M2 exists before calling it Class.forName("myPack2.M2").getMethod("print").invoke(null); } catch (Exception e) { System.out.println("M2 isn't available, skipping that part"); } System.out.println("I am M1 Again"); } }
In this case, even without myModuleB, your app would still run—making requires static the right choice.
内容的提问来源于stack exchange,提问作者my name is GYAN

