|
| 1 | +package org.mangorage.bootstrap; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.lang.module.Configuration; |
| 5 | +import java.lang.module.ModuleFinder; |
| 6 | +import java.lang.reflect.Method; |
| 7 | +import java.net.URLClassLoader; |
| 8 | +import java.nio.file.Path; |
| 9 | +import java.util.stream.Collectors; |
| 10 | + |
| 11 | +import static org.mangorage.bootstrap.Bootstrap.fetchJars; |
| 12 | + |
| 13 | +public final class Test { |
| 14 | + public static void main(String[] args) { |
| 15 | + Path libsPath = Path.of("libraries"); |
| 16 | + Path pluginsPath = Path.of("plugins"); |
| 17 | + |
| 18 | + ModuleFinder plugins = ModuleFinder.of(pluginsPath); |
| 19 | + |
| 20 | + ModuleFinder finder = ModuleFinder.of(libsPath, pluginsPath); |
| 21 | + |
| 22 | + Configuration cfg = ModuleLayer.boot() |
| 23 | + .configuration() |
| 24 | + .resolve( |
| 25 | + finder, |
| 26 | + ModuleFinder.of(), |
| 27 | + plugins.findAll() |
| 28 | + .stream() |
| 29 | + .map(ref -> ref.descriptor().name()) |
| 30 | + .toList() |
| 31 | + ); |
| 32 | + |
| 33 | + |
| 34 | + URLClassLoader CL_libraries = new URLClassLoader(fetchJars(new File[]{new File("libraries")}), Thread.currentThread().getContextClassLoader().getParent()); |
| 35 | + URLClassLoader cl = new URLClassLoader(fetchJars(new File[]{new File("plugins")}), CL_libraries); |
| 36 | + Thread.currentThread().setContextClassLoader(cl); |
| 37 | + |
| 38 | + var layer = ModuleLayer.boot().defineModulesWithOneLoader(cfg, cl); |
| 39 | + callMain("org.mangorage.entrypoint.MangoBotCore", args, cl, layer); |
| 40 | + } |
| 41 | + |
| 42 | + public static void callMain(String className, String[] args, ClassLoader classLoader, ModuleLayer moduleLayer) { |
| 43 | + try { |
| 44 | + Class<?> clazz = Class.forName(moduleLayer.findModule("org.mangorage.mangobotcore").get(), className); |
| 45 | + Method mainMethod = clazz.getMethod("main", String[].class); |
| 46 | + |
| 47 | + // Make sure it's static and public |
| 48 | + if (!java.lang.reflect.Modifier.isStatic(mainMethod.getModifiers())) { |
| 49 | + throw new IllegalStateException("Main method is not static, are you high?"); |
| 50 | + } |
| 51 | + |
| 52 | + // Invoke the main method with a godawful cast |
| 53 | + mainMethod.invoke(null, (Object) args); |
| 54 | + } catch (Exception e) { |
| 55 | + e.printStackTrace(); |
| 56 | + throw new RuntimeException("Couldn't reflectively call main because something exploded.", e); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments