Skip to content

Instantly share code, notes, and snippets.

@i-sannikov
Created January 23, 2018 11:55
Show Gist options
  • Save i-sannikov/badc6d0798b145123897a68ae4e3d6bd to your computer and use it in GitHub Desktop.
Save i-sannikov/badc6d0798b145123897a68ae4e3d6bd to your computer and use it in GitHub Desktop.
JAVA9 load module in runtime
import java.lang.module.ModuleFinder;
import java.lang.module.ModuleReference;
import java.lang.reflect.Method;
import java.util.Optional;
public class LoadModule {
public static void main(String[] args) throws Exception {
load("java.activation");
}
public static void load(String name) throws Exception {
Optional<ModuleReference> ref = ModuleFinder.ofSystem().find(name);
ModuleLayer boot = ModuleLayer.boot();
Module m = boot.findModule("java.base").get();
ClassLoader scl = ClassLoader.getSystemClassLoader();
Method addOpens = m.getClass().getDeclaredMethod("implAddOpens", String.class);
addOpens.setAccessible(true);
addOpens.invoke(m, "jdk.internal.loader");
Method loadModule = scl.getClass().getMethod("loadModule", ModuleReference.class);
loadModule.invoke(scl, ref.get());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment