Question

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?

Was it helpful?

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());

OTHER TIPS

Maybe it's because you try to load that interface from the "dynamic classes"-path? What happens when you drop your interface in there, too?

Probably because you're using a different class loader, and it's not finding the classes loaded by it's classloader.

Have you considered using a SPI for this instead? http://download.oracle.com/javase/1.4.2/docs/guide/jar/jar.html#Service%20Provider (sorry for the old link, but the approach is the same.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top