Search code examples
javajava-modulejava-platform-module-system

How to test whether an optional module is present at runtime


The Java Platform Module System (JPMS) allows a module to declare an optional dependency using requires static in the module-info.java file:

module my.module {
    requires static some.optional.module;
}

However, how should you check in your code whether the module is present at runtime?

The Project Jigsaw: Optional Modules page proposed:

public boolean isModulePresent(String mn);

But, it appears that was dropped because there is no such method in the latest Java releases. Neither am I able to find the @RequireOptionalModule annotation mentioned there in the current Java version.

This example on blog@CodeFX suggests a quite verbose method chain on StackWalker (which is explained here).
Edit: That example tries to find out if a module is available to the caller class, which is not necessary in my case.

Is there an easier way to perform this check, or can a simple Class.forName check suffice if the presence of a certain class indicates that a module is present?


Solution

  • To find out if some module is available at runtime, you can simply call ModuleLayer.findModule():

    Optional<Module> module = ModuleLayer.boot().findModule("java.desktop");
    System.out.println(module.isPresent());
    

    Class.forName() should work too if you know the name of some specific class from the module. However, forName() throws ClassNotFoundException if a class is not found. This means you will have to surround it with try-catch to make it work. This is not very convenient.