如何在 Java 9 中以编程方式获取所有模块的列表?

How to get list of all modules programmatically in Java 9?

如何通过Java代码获取当前JVM实例中所有模块的列表?可能吗?如果是,那又如何?

使用 jar 或模块目录作为应用程序的输入,您可以使用 ModuleFinder to start off with and further making use of the findAll 来查找 此查找器引用的所有模块的集合可以定位。

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

这很容易通过命令行选项将模块列为:

java -p <jarfile> --list-modules

不过,如果您不想故意进入 tweaking things with the ModuleLayer and the Configuration of the java.lang.module as pointed out precisely by ,这应该足够了。

ModuleLayer.boot().modules().stream()
                .map(Module::getName)
                .forEach(System.out::println);