Search code examples
javaurlclassloaderdynamic-class-loaders

URLClassLOader unable to load classes from jar dynamically


   URLClassLoader child;
   try {
       child = new URLClassLoader(new URL[]{myJar.toURI().toURL()}, Test2.class.getClassLoader());
       child.loadClass("com.bla.bla.StringUtilService");
   } catch (MalformedURLException | ClassNotFoundException ex) {
       ex.printStackTrace();
   }

I am getting ClassNotFoundException in loadClass.

I have tried several variants of the code such as

URL[] urls = { new URL("jar:file:" + "E:\\Works\\Workspace\\JUnit_Proj\\client.jar"+"!/") };
URLClassLoader cl = URLClassLoader.newInstance(urls);

But all results into ClassNotFoundException!

I have tried debugging in Eclipse, but the class loader instance is unable to load classes from the jar. The classes Vector is empty.


Solution

  • Succeeded using different costructor of URLClassLoader.

    
    
        try {
            File jarFile = new File("D:\\Workspace\\Test\\Test.jar");
            URLClassLoader loader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()});
    
            Class.forName("com.bla.bla.HelloWorld", true, loader);
            System.out.println("Success");
            loader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }