I am trying to compile a java source file using the javac and command line and i want to load it dynamically at runtime using the URLClassLoader but it fails.
My Steps:
- This is the java source file:
package ubl4nk;
import model.User; // <------- This is imported from lib1.jar which i will include in the next step
import runner.Activity; // <------- This is imported from lib2.jar which i will include in the next step
public class Equity {
public void function1() {
// ...
}
public void function2() {
// ...
}
}
- I run this command
javac -classpath lib1.jar;lib2.jar Equity.javaand then i get an outputEquity.classfile. - I create a jar file from
Equity.classusing commandjar -cf myjar.jar *.classand i get the outputmyjar.jar - I want to load the
Equityclass in my program but it throwsjava.lang.ClassNotFoundException: ubl4nk.Equity:
URL[] urls = new URL[]{
new File("C:\\Users\\FX506HC\\Desktop\\mtest\\lib1.jar").toURI().toURL(),
new File("C:\\Users\\FX506HC\\Desktop\\mtest\\lib2.jar").toURI().toURL(),
new File("C:\\Users\\FX506HC\\Desktop\\mtest\\myjar.jar").toURI().toURL()
};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("ubl4nk.Equity");
System.out.println(cls.getName());
>Solution :
When you do
jar -cf myjar.jar *.class
The created jar does not include the nbl4nk folder. It only includes the Equity class, sitting at the root directory of the jar. Without the nbl4nk folder, a URLClassLoader cannot find the nbl4nk package, and hence cannot find nbl4nk.Equity.
Assuming the class file is actually in a folder called nbl4nk, you should instead include the whole folder:
jar -cf myjar.jar .
You can also go up a directory, and run
jar -cf myjar.jar nbl4nk