Reputation: 140
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.
Upvotes: 1
Views: 2640
Reputation: 140
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();
}
Upvotes: 1
Reputation: 4652
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
Upvotes: 0