Search code examples
javaclassurlimportbuildpath

Java: Get a class from an external .jar


I have a problem with getting a class from an external .jar file. I found this method of loading an external .jar here but whenever I run it, I get a ClassNotFoundException. Below is the code I am using and here is the .jar I am testing with. If anyone has any idea about how to fix this please do tell me. Thanks!

Here's my code:

@SuppressWarnings({ "rawtypes", "unchecked", "unused" })
public void loadJar() throws MalformedURLException {
    URL[] classes = {new URL("jar:file://test.jar!/")};
    URLClassLoader child = new URLClassLoader (classes, this.getClass().getClassLoader());
    try {
        Class classToLoad = Class.forName ("test.PackageTest", true, child);
        Method method = classToLoad.getDeclaredMethod ("test");
        Object instance = classToLoad.newInstance();
        Object result = method.invoke(instance);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}

Solution

  • Try breaking URL[] classes = {new URL("jar:file://test.jar!/")}; into a few statements

    File myFile = new File("test.jar");
    URL myJarFileURL = new URL("jar", "", "file:" + myFile.getAbsolutePath() + "!/");
    URL[] classes = {myJarFileURL};
    

    You can send myFile.getAbsolutePath() to a logger or the console and see where the class loader is expecting to find test.jar. Then make sure that test.jar is in that location.