Given the modA.jar file with a properly packaged modA module that has the following structure
└──modA
│ module-info.class
│ module-info.java
│
└───pkg
Main.class
Main.java
and given the following module definition
module modA {
}
and the following pkg.Main class
package pkg;
class Main {
public static void main(String... args) {
System.out.print("Hi");
}
}
and the following command
java -p modA.jar -m modA/pkg.Main
What is the result? Choose one.
A. The command fails. To fix it you need to add the following line to module-info.java:
exports pkg;
B. The command fails. To fix it you need to add the following line to module-info.java:
opens pkg;
C. The command fails. To fix it you need to change the pkg.Main class declaration to the following:
public class Main {
D. The command successfully runs and prints Hi.
Answer. One of the things the Java Platform Module System (JPMS) addresses is encapsulation. Without the module system, Java’s encapsulation boundary choices are very limited—and not particularly strong. A private Java element is the most constrained, but this level of restriction can be bypassed using reflection by default. Package-level accessibility can be bypassed simply by placing a class in the same package, because packages can be split across any number of JAR files anywhere on the classpath. Plus, any public Java element is entirely public throughout the entire running JVM.
That’s where JPMS comes in. The system enforces encapsulation options such that private Java elements are truly private by default: Packages cannot be split across modules, and a public element is accessible only within the same module unless your deliberate directive opens the containing package to other modules.
Despite all this additional encapsulation, the JVM itself still has access to everything. That’s necessary because it mediates accesses between the elements of your code based on the various directives in the source code.
When the JVM wants to access a main method to launch a program, it does not care if the class that contains that method is public or not. It also doesn’t care whether the package containing the class is exported. Knowing this, you can see the command shown for this question would run successfully and print Hi to the console. Therefore, option D is correct.
What about the incorrect options?
Option A suggests a need to export the containing package. This would potentially allow code from other modules access to the public features in that package, but as noted, that is not necessary for this code to run. Therefore, this option is incorrect.
Option B is also incorrect because opening a package potentially allows reflective access from code in another module.
Option C is incorrect because as with nonmodular code, the class containing the main method does not need to be public even though it usually is public as a matter of style.
Conclusion. The correct answer is option D.
Source: oracle.com
0 comments:
Post a Comment