Reputation: 16284
I'm working on a launcher library for Java 9 which uses module layering. In order to add a module in the layer I need to pass the module name (as a String) to the parent's configuration. ModuleLayer
Javadoc has an example just in the end of the class documentation.
Now, instead of forwarding the burden of the user of my library to declare the module names, I would like to allow just passing the jar file location as a String
, URL
, File
, or JarFile
.
So my question, given a JarFile
what would be the easiest way of extracting the module name programmatically; automatic or declared?
Upvotes: 4
Views: 1726
Reputation: 31968
One way I could think of to get to know the names of the module present in a directory is via ModuleFinder.findAll()
method:
Path jarDirectory1, jarDirectory2;
ModuleFinder finder = ModuleFinder.of(jarDirectory1, jarDirectory2);
Set<ModuleReference> moduleReferences = finder.findAll();
Set<String> moduleNames =
moduleReferences.stream().map(mRef -> mRef.descriptor().name()).collect(Collectors.toSet());
Edit:: One-liner for the above as suggested by Alan for a single module(automatic) from its jar could be :
String moduleName = ModuleFinder.of(path_to_jar)
.findAll().stream().findFirst()
.map(ModuleReference::descriptor)
.map(ModuleDescriptor::name)
.orElse(null);
Another way could be to make use of the ToolProvider
and tweak the output stream to be able to store just the module name from :
Optional<ToolProvider> jar = ToolProvider.findFirst("jar");
jar.get().run(
System.out,
System.err,
"--describe-module",
"--file",
"path/to/the/jar/for/example/commons-lang3-3.6.jar"
);
Upvotes: 6