0

How to get java.lang.Module by string name in Java 9?

For example, we have

String name = "some.module";
Module module = //how to get here it?
Naman
  • 27,789
  • 26
  • 218
  • 353
Pavel_K
  • 10,748
  • 13
  • 73
  • 186

1 Answers1

7

One way to get your module from the boot layer which consists at least java.base after its initialization is:

String moduleName = "my.module";
Module m = ModuleLayer.boot().findModule(moduleName).orElse(null);

though preferably a safe way IMO, would be to get a module would be using the Configuration and the system ClassLoader to get the ModuleLayer of your module and then findModule as :

Path path = Paths.get("/path/to/your/module");

ModuleFinder finder = ModuleFinder.of(path);
ModuleLayer parent = ModuleLayer.boot();

Configuration configuration = parent.configuration().resolve(finder, ModuleFinder.of(), Set.of(moduleName));
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();

ModuleLayer layer = parent.defineModulesWithOneLoader(configuration, systemClassLoader);
Module m = layer.findModule(moduleName).orElse(null);
Naman
  • 27,789
  • 26
  • 218
  • 353
  • Do I understand right - once created layer can not be modified? I mean it is not possible to add or remove module to/from it? – Pavel_K Sep 18 '17 at 21:21
  • 2
    @Pavel_K a layer once created can be modified with the updates in the modules info included in it, if that's what you're asking. It's possible to remove/add a module to the layer if you're updating the module-info of your.module. – Naman Sep 18 '17 at 21:23
  • I mean the following - I have modules A and B and I create layer with these two module. Can I later 1) add new module to this layer? 2) remove module A from this layer? 3) update module A in this layer? – Pavel_K Sep 18 '17 at 21:25
  • 2
    @Pavel_K Yes the layer would be modified with updates to the configuration as you do any of those actions. – Naman Sep 18 '17 at 21:26
  • I have seen this sort of method promoted in several places. However, it seems to require hard-coding the module path in the source code, which defeats the purpose of having a classpath (or module path in Java 9), which allows you to change which jar (or module) you depend upon when you launch the JRE. How is your second method better than your first method? (The second method is really an example of dynamic loading of modules.) Also, I think your first method won't work if there are multiple layers of modules? – Luke Hutchison Dec 24 '17 at 08:35