简体   繁体   中英

How to get a Module by its name in Java 9?

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM