How to get a Module object from a ModuleReference

两盒软妹~` 提交于 2019-12-07 07:46:02

问题


Using the code:

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

I am able to retrieve a Set<ModuleReference> of all the .jars in the path folder.

My next step would be getting a Module from a ModuleReference but there's no method that returns that, I can get a ModuleDescriptor but even that one doesn't help. Is there a way to do this?


回答1:


If you desire to access the module content you should open the ModuleReference that you've attained. This would provide you access to the ModuleReader which

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.

Do keep in mind though, that the docs also specify :

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.


One way to get the Module from the resources would be to access it using the Class#getModule as:

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

Edit: I've learned with time a better way to use the ModuleFinder to access a Module as suggested by @Alan as well could possibly be :

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



回答2:


The classes in java.lang.module are more model world. Look at j.l.module.Configuration and also j.l.ModuleLayer to see how to create a configuration and instantiate it in the Java virtual machine as a layer of modules. There is a code fragment in the ModuleLayer javadoc that might get you going, just bewarned that this is an advanced topic and best to master the basics first.



来源:https://stackoverflow.com/questions/46180116/how-to-get-a-module-object-from-a-modulereference

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