I know there are already a lot similar questions here, but I couldn't get any smarter form them. I want to load a class inside a jar file, at this point this is no problem, but when I want to pass the path to my own ClassLoader it throws an exception it cannot find the class. Is it possible to load a class inside a jar using an absolute path? For instance,Class cls = loader.loadClass(/path/MyPlugin.jar/MyPlugin.class);
But when I do this:
File test = new File("path/plugins/MyPlugin.jar/MyPlugin.class");
System.out.println(test.exists());
It prints out false. I tried using MyPlugin.jar!/MyPlugin.class
or MyPlugin.jar.jar!MyPlugin.class
which i've seen sometimes on the web, even though i don't really know what it means...
When I do this it finds the class:
URLClassLoader loader = new URLClassLoader(new URL[] { "path/plugins/MyPlugin.jar" });
Class cl = loader.loadClass("MyPlugin");
But now, how can I receive the path? Something like URL url = cl.getResource("MyPlugin");
(which gives back a null)
You can obtain URLs to classpath resources using ClassLoader.getResources. To find a jar with specific class, you may use the following
where
classLoader
is any classloader capable of finding the class you want to load. If the jar is a part of your application's classpath, you may use system classloader:Otherwise, you need to know the jar file location beforehand, and create an instance of
URLClassLoader
, passing the jar in the constructor:and then use it to load your class.