Class 在 Jar 内部创建 Class 的新实例时未发现异常 - Java

Class Not Found Exception When Creating New Instance Of Class Inside of Jar - Java

我正在尝试创建 class 的新实例以调用 Java 中的方法。但是因为 class 在一个罐子里(可以很好地加载),所以 class 不能。这会导致抛出 ClassNotFoundException。有人可以告诉我如何解决这个问题吗?

代码:

private static void loadClassFromJar(String PluginJar) throws MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
    File PluginFile = new File("./debug/plugins/DiamondCorePlugin.jar");
    URL[] PluginURLs = { PluginFile.getAbsoluteFile().toURI().toURL() };
    URLClassLoader ClassLoader = URLClassLoader.newInstance(PluginURLs);
    Class<?> PluginClass = ClassLoader.loadClass("net.trenterprises.diamondcore.plugin.Main");
    Method EventMethod = PluginClass.getMethod("onEnable");
    EventMethod.invoke(PluginClass.newInstance());
}

堆栈跟踪:

java.lang.ClassNotFoundException: net.trenterprises.diamondcore.plugin.Main
at java.net.URLClassLoader.run(URLClassLoader.java:372)
at java.net.URLClassLoader.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:260)
at net.trenterprises.diamondcore.cross.api.javaplugin.sub.Server.getClassCaller(Server.java:23)
at net.trenterprises.diamondcore.cross.api.javaplugin.sub.Server.getLogger(Server.java:15)
at net.trenterprises.diamondcore.plugin.Main.onEnable(Main.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at net.trenterprises.diamondcore.cross.api.PluginLoader.loadClassFromJar(PluginLoader.java:55)
at net.trenterprises.diamondcore.cross.api.PluginLoader.loadAllPlugins(PluginLoader.java:25)
at net.trenterprises.diamondcore.DiamondCoreServer.<init>(DiamondCoreServer.java:47)
at net.trenterprises.diamondcore.run.main(run.java:15)

找到问题了!事实证明 class 加载得很好,但在另一个试图获取 classes 名称的 class 中,因为 class 在 JAR 文件中。它无法加载!感谢 immibiz 和 vanza 的所有帮助!