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

时间:2016-04-23 18:11:41

标签: java bukkit

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

我有一个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中的Main Application运行方法,但是我不能使用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()});

1 个答案:

答案 0 :(得分:0)

我通过将类加载到插件的类加载器而不是它自己的类加载器或System类加载器来解决了这个问题。现在完美无瑕。