164. Inspecting modules

Java 9 has added the concept of modules via the Java Platform Module System. Basically, a module is a set of packages managed by that module (for example, the module decides which packages are visible outside the module).

An application with two modules can be shaped as in the following screenshot:

There are two modules—org.player and org.tournament. The org.player module requires the org.tournament module, and the org.tournament module exports the com.management package.

Java Reflection API represents a module via the java.lang.Module class (in the java.base module). Via the Java Reflection API, we can extract information or modify a module.

For start, we can obtain a Module instance as in the following two examples:

Module playerModule = Player.class.getModule();
Module managerModule = Manager.class.getModule();

The name of a module can be obtained via the Module.getName() method:

// org.player
System.out.println("Class 'Player' is in module: "
+ playerModule.getName());

// org.tournament
System.out.println("Class 'Manager' is in module: "
+ managerModule.getName());

Having a Module instance, we can call several methods for getting different information. For example, we can find out whether a module is named or it has exported or opened a certain package:

boolean playerModuleIsNamed = playerModule.isNamed();   // true
boolean managerModuleIsNamed = managerModule.isNamed(); // true

boolean playerModulePnExported
= playerModule.isExported("com.members"); // false
boolean managerModulePnExported
= managerModule.isExported("com.management"); // true

boolean playerModulePnOpen
= playerModule.isOpen("com.members"); // false
boolean managerModulePnOpen
= managerModule.isOpen("com.management"); // false

Beside getting information, the Module class allows us to alter a module. For example, the org.player module doesn't export the com.members package to the org.tournament module. We can check this quickly:

boolean before = playerModule.isExported(
"com.members", managerModule); // false

But we can alter this via reflection. We can perform this export via the Module.addExports() method (in the same category we have addOpens(), addReads(), and addUses()):

playerModule.addExports("com.members", managerModule);

Now, let's check again:

boolean after = playerModule.isExported(
"com.members", managerModule); // true

A module also takes advantages of its own descriptor. The ModuleDescriptor class can be used as the starting point for working with a module:

ModuleDescriptor descriptorPlayerModule 
= playerModule.getDescriptor();

For example, we can fetch the packages of a module as follows:

Set<String> pcks = descriptorPlayerModule.packages();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.71.28