19

How can I get list of all modules in current JVM instance via Java code? Is it possible? If yes, then how?

Pavel_K
  • 10,748
  • 13
  • 73
  • 186

2 Answers2

18
ModuleLayer.boot().modules().stream()
                .map(Module::getName)
                .forEach(System.out::println);
Alan Bateman
  • 5,283
  • 1
  • 20
  • 25
  • 3
    This is only true if there boot layer is the only layer. If modules are loaded by different class loaders, this list will be incomplete. – Rafael Winterhalter Sep 18 '17 at 08:51
  • 3
    Sure, but the code fragment will get the person asking the question started. There are of course APIs for tools and debuggers to enumerate all modules in the VM, including unnamed modules, but that is way beyond what I suspect the question is about. – Alan Bateman Sep 18 '17 at 09:04
  • 1
    I disagree, Alan Bateman -- this answer is incomplete. As you hint in your comment, this does not even return unnamed modules or automatic modules, which are and will continue to be very common during the early years of Java 9. – Luke Hutchison Dec 22 '17 at 23:30
  • 1
    Luke - automatic modules are named modules. If there are any automatic modules in the boot layer then they will be included. – Alan Bateman Dec 27 '17 at 15:50
7

Using a jar or directory of modules as an input for your application, you can possibly use a ModuleFinder to start off with and further making use of the findAll to find the set of all module references that this finder can locate.

Path dir1, dir2, dir3;
ModuleFinder finder = ModuleFinder.of(dir1, dir2, dir3);
Set<ModuleReference> moduleReferences = finder.findAll();

This is easily possible with the command line option to list the modules as:

java -p <jarfile> --list-modules

which should be sufficient though, if you do not want to intentionally get into tweaking things with the ModuleLayer and the Configuration of the java.lang.module as pointed out precisely by @Alan's answer.

Naman
  • 27,789
  • 26
  • 218
  • 353