javaurlclassloader

URLClassLoader is unable to load class in java


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:

  1. 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() {
           // ...
    }
        
}
  1. I run this command javac -classpath lib1.jar;lib2.jar Equity.java and then i get an output Equity.class file.
  2. I create a jar file from Equity.class using command jar -cf myjar.jar *.class and i get the output myjar.jar
  3. I want to load the Equity class in my program but it throws java.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