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());
When you do
The created jar does not include the
nbl4nkfolder. It only includes theEquityclass, sitting at the root directory of the jar. Without thenbl4nkfolder, aURLClassLoadercannot find thenbl4nkpackage, and hence cannot findnbl4nk.Equity.Assuming the class file is actually in a folder called
nbl4nk, you should instead include the whole folder:You can also go up a directory, and run