Load class within Jar file and get it's path

domizai picture domizai · Sep 3, 2013 · Viewed 12.8k times · Source

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)

Answer

Marcin Łoś picture Marcin Łoś · Sep 3, 2013

You can obtain URLs to classpath resources using ClassLoader.getResources. To find a jar with specific class, you may use the following

URL url = classLoader.getResource("com/example/SomeClass.class");
JarURLConnection connection = (JarURLConnection) url.openConnection();
JarFile file = connection.getJarFile();
String jarPath = file.getName();

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:

ClassLoader classLoader = ClassLoader.getSystemClassloader();

Otherwise, you need to know the jar file location beforehand, and create an instance of URLClassLoader, passing the jar in the constructor:

ClassLoader classLoader = new URLClassLoader(new URL[]{new URL("path/to/the/jar/file.jar")});

and then use it to load your class.