Running module jar programatically

Alan Bateman Alan.Bateman at
Wed Dec 2 16:29:14 UTC 2015

On 02/12/2015 15:24, Stephane Epardaud wrote:
> Hi,
> I have a modular jar produced by Java 9 EA + Jigsaw, I can run it with
> "java -mp mlib -m my.module", but how can I run it programmatically in Java?
> ATM I'm using URLClassLoader to load it and run it, but I _think_ it
> does not make it "modular" and the module package visibility checks are
> turned off.
> What should I be looking at to load this module at runtime and run it as
> a Java module?

Below is a code fragment to get you started. It assumes a collection of 
modules in a directory and you know the name of the main/initial module. 
It creates a Configuration by resolving that module by name. That module 
might have dependences on other modules in the directory, maybe 
dependences on modules in what we call the boot layer. This code 
fragments use ModuleClassLoader, that might go away as it's not really 
needed. Anyway, might get you started.


         Path dir =  ...

         String moduleName = ...

         ModuleFinder finder = ModuleFinder.of(dir);

         Configuration cf = Configuration.resolve(finder,

         ModuleClassLoader loader = new ModuleClassLoader(cf);

         Layer layer = Layer.create(cf, Layer.boot(), mn -> loader);

         Optional<Module> om = layer.findModule(moduleName);
         Module mainModule = om.get();
         Optional<String> omc = mainModule.getDescriptor().mainClass();
         String mainClass = omc.get();
         Class<?> c = mainModule.getClassLoader().loadClass(mainClass);

More information about the jigsaw-dev mailing list