简体   繁体   中英

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

I am trying to create a new instance of a class to invoke a method in Java. But because the class is inside a jar (Which loads just fine), The class cannot. This causes a ClassNotFoundException to be thrown. Could someone please tell me how to fix this?

Code:

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());
}

Stack trace:

java.lang.ClassNotFoundException: net.trenterprises.diamondcore.plugin.Main
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.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)

Found the problem! It turned out that the class was loading just fine, but in another class that tried to get the classes name, becuase the class was in a JAR file. It could not load! Thank you for all of the help immibiz and vanza!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM