Main.java

import java.lang.module.Configuration; import java.lang.module.ModuleFinder; import java.lang.reflect.Method; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Set; public class Main { private static final String MODULE_NAME = "demo"; private static final String CLASS_NAME = "io.vividcode.demo.version.Version"; private static final String METHOD_NAME = "getVersion"; public static void main(final String[] args) { final Main main = new Main(); main.load(Paths.get("dist", "v1")); main.load(Paths.get("dist", "v2")); } public void load(final Path path) { showVersion(createLayer(path)); } private void showVersion(final ModuleLayer moduleLayer) { try { final Class<?> clazz = moduleLayer.findLoader(MODULE_NAME) .loadClass(CLASS_NAME); final Method method = clazz.getDeclaredMethod(METHOD_NAME); System.out.println(method.invoke(null)); } catch (final Exception e) { e.printStackTrace(); } } private ModuleLayer createLayer(final Path path) { final ModuleLayer parent = ModuleLayer.boot(); final Configuration configuration = parent.configuration().resolve( ModuleFinder.of(path), ModuleFinder.of(), Set.of(MODULE_NAME) ); return parent.defineModulesWithOneLoader(configuration, ClassLoader.getSystemClassLoader()); } }
Using ModuleLayer to Load Modules

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.