简体   繁体   中英

Why don't I have to require java.base?

When I try to import javax.swing.JFrame , eclipse complains because I need to explicitly tell my package that I'm going to import stuff from the java.desktop module. So I put requires java.desktop in my module-info.java and then the java compiler knows to link up the java.desktop stuff. I can put requires java.base in my module-info.java as well, but it doesn't seem to be necessary. I can import java.util.Arrays without it.

Is eclipse adding some magic sauce to my javac options behind the scenes? Does javac automagically require java.base ? Why don't I need to require java.base ? If this is compiler magic, are there any other such privileged modules that get automatically linked into my package?

Using jdk-14, but not sure if that's relevant.

This is specified in JLS 7.7.1 :

7.7.1. Dependences
The requires directive specifies the name of a module on which the current module has a dependence.
A requires directive must not appear in the declaration of the java.base module, or a compile-time error occurs, because it is the primordial module and has no dependences (§8.1.4).
If the declaration of a module does not express a dependence on the java.base module, and the module is not itself java.base, then the module has an implicitly declared dependence on the java.base module.

This is similar to how classes from the java.lang package are implicitly imported into source files. Modules do not need to explicitly declare that they depend on the java.base module.

This is because all platform modules provided by JVM are observable module. By default if you are creating your module you don't need to require these platform module. Packages exported by these modules can be imported without any require directive in module-info.java file. You can get the list of observable/platform module using this command.

java --list-modules

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM