如何加载不在类路径中且在 jar 中的类?

我想加载一个在罐子里的类。


我已经尝试使用此代码加载类:


URL dirUrl = jarFile.toURL();

URLClassLoader ucl = new URLClassLoader(new URL[] {dirUrl}, getClass().getClassLoader());

Class<?> clazz = ucl.loadClass(mainClass);

ucl.close();

我得到一个例外,它找不到课程:


java.lang.RuntimeException: java.lang.ClassNotFoundException: net.api.main

        at net.al.Main.onEnable(Main.java:39) ~[?:?]

        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321) ~[spigot.jar:git-Spigot-db6de12-18fbb24]

        at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:340) [spigot.jar:git-Spigot-db6de12-18fbb24]

        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405) [spigot.jar:git-Spigot-db6de12-18fbb24]

        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.loadPlugin(CraftServer.java:357) [spigot.jar:git-Spigot-db6de12-18fbb24]

        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.enablePlugins(CraftServer.java:317) [spigot.jar:git-Spigot-db6de12-18fbb24]

        at org.bukkit.craftbukkit.v1_8_R3.CraftServer.reload(CraftServer.java:741) [spigot.jar:git-Spigot-db6de12-18fbb24]

        at org.bukkit.Bukkit.reload(Bukkit.java:535) [spigot.jar:git-Spigot-db6de12-18fbb24]


慕斯王
浏览 112回答 2
2回答

海绵宝宝撒

我通过将 jar 添加到类路径来修复它。文件到 jar 路径的代码:public static void addURLToClassPath(URL url) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; URLClassLoader classLoader = (URLClassLoader) MyClass.class.getClassLoader();&nbsp; &nbsp; &nbsp; &nbsp; @SuppressWarnings("rawtypes")&nbsp; &nbsp; &nbsp; &nbsp; Class clazz = URLClassLoader.class;&nbsp; &nbsp; &nbsp; &nbsp; @SuppressWarnings("unchecked")&nbsp; &nbsp; &nbsp; &nbsp; Method method = clazz.getDeclaredMethod("addURL", new Class[] { URL.class });&nbsp; &nbsp; &nbsp; &nbsp; method.setAccessible(true);&nbsp; &nbsp; &nbsp; &nbsp; method.invoke(classLoader, new Object[] { url });&nbsp; &nbsp; }

紫衣仙女

请检查net.api.main是否存在或者检查变量 jarFile 和 mainClass
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java