问题
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?
回答1:
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);
来源:https://stackoverflow.com/questions/46287644/how-to-get-a-module-by-its-name-in-java-9