1
   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.

Roman C
  • 49,761
  • 33
  • 66
  • 176
javaCurious
  • 140
  • 2
  • 14

2 Answers2

1

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();
    }

javaCurious
  • 140
  • 2
  • 14
0

The class is a direct child of the dir in the url, so you need no package.

Try this without the package. Like this:

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

Also, try like this:

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

Solution from: ClassNotFoundException while loading a class from file with URLClassLoader

Community
  • 1
  • 1
viniciussss
  • 4,404
  • 2
  • 25
  • 42