5

Using the code:

ModuleFinder.of(Paths.get(path)).findAll() 

I am able to retrieve a Set<ModuleReference> of all the .jars in the path folder.

My next step would be getting a Module from a ModuleReference but there's no method that returns that, I can get a ModuleDescriptor but even that one doesn't help. Is there a way to do this?

Naman
  • 27,789
  • 26
  • 218
  • 353
MrSir
  • 576
  • 2
  • 11
  • 29

2 Answers2

4

If you desire to access the module content you should open the ModuleReference that you've attained. This would provide you access to the ModuleReader which

is intended for cases where access to the resources in a module is required

A resource in a module is identified by an abstract name that is a '/'-separated path string. For example, module java.base may have a resource "java/lang/Object.class" that, by convention, is the class file for java.lang.Object. A module reader may treat directories in the module content as resources (whether it does or not is module reader specific). Where the module content contains a directory that can be located as a resource then its name ends with a slash ('/'). The directory can also be located with a name that drops the trailing slash.

Do keep in mind though, that the docs also specify :

A ModuleReader is open upon creation and is closed by invoking the close method. Failure to close a module reader may result in a resource leak. The try-with-resources statement provides a useful construct to ensure that module readers are closed.


One way to get the Module from the resources would be to access it using the Class#getModule as:

Module module = com.foo.bar.YourClass.class.getModule();

Edit: I've learned with time a better way to use the ModuleFinder to access a Module as suggested by @Alan as well could possibly be :

ModuleFinder finder = ModuleFinder.of(path);
ModuleLayer parent = ModuleLayer.boot();
Configuration configuration = parent.configuration().resolve(finder, ModuleFinder.of(), Set.of("curious")); // 'curious' being the name of the module
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
ModuleLayer layer = parent.defineModulesWithOneLoader(configuration, systemClassLoader);

Module m = layer.findModule("curious").orElse(null);
Naman
  • 27,789
  • 26
  • 218
  • 353
3

The classes in java.lang.module are more model world. Look at java.lang.module.Configuration and also java.lang.ModuleLayer to see how to create a configuration and instantiate it in the Java virtual machine as a layer of modules. There is a code fragment in the ModuleLayer javadoc that might get you going, just be warned that this is an advanced topic and best to master the basics first.

Alan Bateman
  • 5,283
  • 1
  • 20
  • 25