使用动态加载的 jar 中的主 jar 方法



我正在为插件制作一个模块。主应用程序加载插件,然后为我的插件加载模块(主应用程序 --加载插件 ->我的插件 --加载模块 ->我的模块)。

我有一个jar(我们称之为dynamicJar),我正在动态加载到我的插件中。我遇到的问题是,当我想在 dynamicJar 中使用插件中的方法和类时,我收到 NoClassDefFound 错误:

Caused by: java.lang.NoClassDefFoundError: me/venom/crates/objects/crates/Crate
at me.venom.csgo.CSGOCrate.runCSGO(CSGOCrate.java:135) ~[CSGOCrates.jar:?]
at me.venom.crates.CSGOHelper.runCSGO(CSGOHelper.java:58) ~[?:?]
at me.venom.crates.PListener.onChestInteract(PListener.java:194) ~[?:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_75]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_75]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_75]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_75]
at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:306) ~[spigot-1.9.jar:git-Spigot-1480adb-8b61cc5]
... 17 more
Caused by: java.lang.ClassNotFoundException: me.venom.crates.objects.crates.Crate
at java.net.URLClassLoader$1.run(URLClassLoader.java:366) ~[?:1.7.0_75]
at java.net.URLClassLoader$1.run(URLClassLoader.java:355) ~[?:1.7.0_75]
at java.security.AccessController.doPrivileged(Native Method) ~[?:1.7.0_75]
at java.net.URLClassLoader.findClass(URLClassLoader.java:354) ~[?:1.7.0_75]
at java.lang.ClassLoader.loadClass(ClassLoader.java:425) ~[?:1.7.0_75]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) ~[?:1.7.0_75]
at java.lang.ClassLoader.loadClass(ClassLoader.java:358) ~[?:1.7.0_75]
at me.venom.csgo.CSGOCrate.runCSGO(CSGOCrate.java:135) ~[CSGOCrates.jar:?]
at me.venom.crates.CSGOHelper.runCSGO(CSGOHelper.java:58) ~[?:?]
at me.venom.crates.PListener.onChestInteract(PListener.java:194) ~[?:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_75]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_75]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_75]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_75]
at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:306) ~[spigot-1.9.jar:git-Spigot-1480adb-8b61cc5]
... 17 more

问题是我可以从 dynamicJar 内部的主应用程序运行方法,但我不能使用 dynamicJar 内部插件中的方法。

TL;DR:使用来自插件jar的类,当从动态加载的jar中使用ClassNotFoundException和NoClassDefFoundError时,会抛出它们。

编辑:

这是我用来将 jar 加载到我的类路径中的代码。

    Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
    method.setAccessible(true);
    method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{file.toURI().toURL()});

我通过将类加载到插件的类加载器中而不是它自己的类加载器或系统类加载器中来解决此问题。现在工作完美无缺。

最新更新