如何在Java 9中按其名称获取模块? [英] How to get a Module by its name in Java 9?
本文介绍了如何在Java 9中按其名称获取模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Java 9中按字符串名称获取java.lang.Module
?
How to get java.lang.Module
by string name in Java 9?
例如,我们有
String name = "some.module";
Module module = //how to get here it?
推荐答案
从引导层获取模块的一种方法是:初始化后至少包含java.base
的引导层是
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);
尽管IMO最好是一种安全的方式,但要使用Configuration
和系统ClassLoader
来获取模块,则要使用
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);
这篇关于如何在Java 9中按其名称获取模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文