java - 如何从 ModuleReference 获取 Module 对象

标签 java java-9

使用代码:

ModuleFinder.of(Paths.get(path)).findAll() 

我能够检索到 Set<ModuleReference> path 中的所有.jars文件夹。

我的下一步是获得 Module来自 ModuleReference 但是没有返回那个的方法,我可以得到一个 ModuleDescriptor 但即使是那个也无济于事。有办法做到这一点吗?

最佳答案

如果您想访问模块内容,您应该open您获得的 ModuleReference。 这将使您可以访问 ModuleReader哪个

is intended for cases where access to the resources in a module is required

A resource in a module is identified by an abstract name that is a '/'-separated path string. For example, module java.base may have a resource "java/lang/Object.class" that, by convention, is the class file for java.lang.Object. A module reader may treat directories in the module content as resources (whether it does or not is module reader specific). Where the module content contains a directory that can be located as a resource then its name ends with a slash ('/'). The directory can also be located with a name that drops the trailing slash.

请记住,文档还指定:

A ModuleReader is open upon creation and is closed by invoking the close method. Failure to close a module reader may result in a resource leak. The try-with-resources statement provides a useful construct to ensure that module readers are closed.


从资源中获取 Module 的一种方法是使用 Class#getModule 访问它。作为:

Module module = com.foo.bar.YourClass.class.getModule();

编辑:随着时间的推移,我学会了使用 ModuleFinder 访问 Module 的更好方法正如 @Alan 所建议的那样也可能是:

ModuleFinder finder = ModuleFinder.of(path);
ModuleLayer parent = ModuleLayer.boot();
Configuration configuration = parent.configuration().resolve(finder, ModuleFinder.of(), Set.of("curious")); // 'curious' being the name of the module
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
ModuleLayer layer = parent.defineModulesWithOneLoader(configuration, systemClassLoader);

Module m = layer.findModule("curious").orElse(null);

关于java - 如何从 ModuleReference 获取 Module 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46180116/

相关文章:

Java 访问实例化的对象

java - 使用 JNI 构建 C++ Java 包装器

java - 如何更改按钮图像,如切换按钮 RecyclerView 按钮以编程方式单击

Java 9 模块系统

java - 什么是 sjavac,它适用于谁以及如何使用它?

Java PaintComponent 正在运行但不显示

java - 如何在 Android 中执行网页抓取?

java - NoClassDefFoundError : Unable to load class groovy. xml.jaxb.JaxbGroovyMethods 由于缺少依赖项 javax/xml/bind/Unmarshaller

java - 提交方法不会调用 onNext FLOW STREAM API JAVA

Java9多模块Maven项目测试依赖