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

强颜欢笑 提交于 2019-12-08 11:48:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!