IntelliJ中Java 9的Module Path与Classpath配置及模块类型咨询
Great questions about Java 9 module configuration in IntelliJ—let’s break this down step by step, since the module system can feel a bit tricky at first!
1. Does IntelliJ have a dedicated Module Path configuration option?
Absolutely—IntelliJ fully supports Java 9’s module system, and it makes setting up the Module Path super intuitive:
- Open Project Structure (use
Ctrl+Alt+Shift+Son Windows/Linux, orCmd+;on macOS—way faster than navigating through menus). - Head to Modules, pick the module you’re working on, then switch to the Dependencies tab.
- You’ll immediately see two separate sections: Module Path and Classpath. When adding libraries or JARs:
- Click the
+button, select JARs or directories, and choose your file. - A small pop-up will let you explicitly choose whether to add the item to the Module Path or Classpath.
- Click the
For Java 9+ projects, IntelliJ automatically enables the module system by default (especially if you’ve added a module-info.java file), so this setup panel will be ready to use right out the gate.
2. Should I keep both Classpath and Module Path configured in IntelliJ?
Yes, and this aligns perfectly with how Java 9 resolves classes:
- Java 9 first searches for classes in modules on the Module Path. If it can’t find what it needs there, it falls back to the Classpath (which acts as the "unnamed module").
- Use the Module Path for modular dependencies (JARs with a
module-info.classfile) or legacy JARs you want to treat as automatic modules (more on that in the next section). - Stick the Classpath for non-modular, old-school code that doesn’t fit into the module system, or dependencies you don’t want to expose as modules.
IntelliJ handles both paths smoothly—they don’t conflict, and the JVM follows its standard resolution order when looking for classes. So keeping both is not just allowed, it’s often necessary in projects that mix modular and non-modular code.
3. When adding a Java 8 JAR to IntelliJ, is it treated as an unnamed module or automatic module?
This depends entirely on which path you add the JAR to:
- Added to the Module Path: The JAR becomes an automatic module. Java 9 generates a module name from the JAR’s filename (usually stripping version numbers and replacing hyphens with dots—for example,
my-utils-2.3.jarbecomesmy.utils). You can then reference this automatic module in your project’smodule-info.javawith a line likerequires my.utils;. - Added to the Classpath: The JAR becomes part of the unnamed module. This module exports all its packages, but if your project is modular (has a
module-info.java), you’ll need to add the VM option--add-modules ALL-UNNAMEDto let your modular code access classes from the unnamed module. If your project isn’t modular (nomodule-info.java), it’ll also be part of the unnamed module, so access works just like it did in Java 8.
内容的提问来源于stack exchange,提问作者darcula

