3

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?

3 Answers 3

3

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());
Sign up to request clarification or add additional context in comments.

2 Comments

I had almost mentioned in my question the possibility of "appending" the classpath classloader to the URLClassLoader. I'm only somewhat familiar with the jargon, but your approach sounds plausible. I'll give it a shot and let you know. Thanks.
This helped me out a lot too - it was driving me a bit mad. Cheers :) x.
0

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?

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.