Search code examples
javamavenurlclassnotfoundexceptionurlclassloader

ClassNotFound with URLClassLoader loading a Jar


Using the following code I get a ClassNotFoundException

File jarFile = new File(jar);
      URL jarUrl = new URL("jar", "", jarFile.getAbsolutePath() + "!/");

URLClassLoader loader = new URLClassLoader(
      new URL[] {jarUrl}, ClassLoader.getSystemClassLoader());

Class<? extends Animal> clazz =
      (Class<? extends Animal>)loader.loadClass("com.mycompany.dog.Dog");

The contents of the Jar are as follows:

META-INF/ 
META-INF/MANIFEST.MF 
com/ 
com/mycompany/ 
com/mycompany/dog/ 
com/mycompany/dog/Dog$1.class 
com/mycompany/dog/Dog.class 
META-INF/maven/ 
META-INF/maven/com.mycompany.app/ 
META-INF/maven/com.mycompany.app/dog/ 
META-INF/maven/com.mycompany.app/dog/pom.xml 
META-INF/maven/com.mycompany.app/dog/pom.properties 
com/mycompany/app/ 
com/mycompany/app/Animal.class 
com/mycompany/app/ActionLog.class 
META-INF/maven/com.mycompany.app/animal/ 
META-INF/maven/com.mycompany.app/animal/pom.xml 
META-INF/maven/com.mycompany.app/animal/pom.properties

Am I doing something wrong?


Solution

  • I would not trust trying to create the Jar URL through the URL constructors, as it may differ from the URL produced by calling File.toURI().toURL() (which forms a valid URL).

    Here is an example.

    import java.net.URL;
    import java.io.File;
    
    public class JarURL {
    
        public static void main(String[] args) throws Exception {
            File f = new File("C:\\the.jar");
            URL jarUrl1 = new URL("jar", "", f.getAbsolutePath() + "!/");
            URL jarUrl2 = f.toURI().toURL();
            System.out.println("jarUrl1: " + jarUrl1);
            System.out.println("jarUrl2: " + jarUrl2);
        }
    }
    

    Produces output:

    jarUrl1: jar:C:\the.jar!/
    jarUrl2: file:/C:/the.jar