How to get Java 9 ModuleReference for an unnamed module

What is the correct way to get ModuleReferenceonly an object Modulein Java 9?

Consider these two methods of accessing java.base:

Module mod = ModuleLayer.boot().findModule("java.base").orElse(null);
ModuleReference modRef = ModuleFinder.ofSystem().find("java.base").orElse(null);

modhas a method Set<String> getPackages(), but you only get package names, you cannot list resources in each package.

modRefhas a method ModuleReader open(), but ModuleReaderhas a method Stream<String> list()that lists the resources in the module, what do I need to do.

However, for automatic (and therefore unnamed) modules created by adding non-modular jarfiles to the classpath, you cannot get ModuleReferencefrom ModuleFinder.ofSystem().find(String name)or ModuleFinder.ofSystem().findAll()- you can only get a Modulelink from getClass().getModule().

I can not find a way to get ModuleReferencefor automatic modules. I also cannot find a way to get ModuleReferencefrom the object Module, which means that I cannot list the resources in Moduleif the module is automatic and / or unnamed.

Surely there should be a way to get ModuleReferencefor a given (already loaded) Module?

+4
source share
2 answers

First of all, to get away from the question that the conclusion is incorrect in the sentence -

for automatic (and therefore unnamed) modules created by adding non-modular jar files to the classpath

, . , , , () .


ClassLoader, , Module ( ). Java 9?. , , , ?

, , , ClassLoader::getUnnamedModule....

ClassLoader cl = getClass().getClassLoader();// returns the class loader for the class
Module yourClassLoaderUnnamedModule = cl.getUnnamedModule();

, , ::

.. , .. getModule loaders unnamed module.

:

Module yourClassUnnamedModule = getClass().getModule(); // from the type itself

, , API, .. , , , pathpath, , , , . , , - , , :

yourClassLoaderUnnamedModule.equals(yourClassUnnamedModule)//true if resource is loaded via classpath
+2

, ModuleFinder.ofSystem(), - , , , JRE, .

, , ModuleFinder.of(path). :

Optional<ResolvedModule> resolvedModule = ModuleLayer.boot().configuration().findModule(name);
Optional<ModuleReference> moduleReference = resolvedModule.map(ResolvedModule::reference);

Module, :

Optional<ModuleReference> moduleReference
     = module.getLayer().configuration()
           .findModule(module.getName())
           .map(ResolvedModule::reference);

, ModuleReference , configuration().modules() , .

+1

Source: https://habr.com/ru/post/1691298/


All Articles