Search code examples
javadynamicclasspathclassloaderclassnotfoundexception

ClassNotFoundException Thrown when Dynamically Loading Class Files


We have a servlet project, which contains (among many other classes) an interface that we expose to users.

Users can compile their own classes (in the form of .class files) that implement the provided interface, and place them in a folder that our project is aware of. When the servlet starts, it uses a URLClassLoader to load all the .class files in that folder. (So users can hook in to certain events.)

As far as I can tell, the class file is located and loaded properly, kind of. When loading the user's compiled .class file, a ClassNotFoundException exception is thrown, but it's complaining about the interface, which should already be on the classpath.

Caused by: java.lang.ClassNotFoundException: com.company.project.OurInterface
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)

When dynamically loading the .class file, is there a reason the interface is not found?


Solution

  • Perhaps you haven't specified parent classloader for your URLClassLoader.

    Your application's classloader should be a parent classloader of your dynamic classloader:

    ClassLoader dynamicClassLoader = 
        new URLClassLoader(..., OutInterface.class.getClassLoader());