Galveston01
Galveston01

Reputation: 356

Java loading JAR dynamically: NoClassDefFoundError

Let's say I have a main class App that loads all jars in the sub-directory plugins using a URLClassLoader:

public class App(){
    public static void main(String[] args){
        for(File f : new File("plugins").listFiles()){
                URL[] urls = { new URL("jar:file:" + "plugins/" + f.getName() + ".jar" + "!/") };
                URLClassLoader cl = URLClassLoader.newInstance(urls);

                Class<?> clazz = cl.loadClass(f.getName().toLowerCase()+"."+f.getName());
                cl.close();
                Plugin p = ((Plugin) clazz.newInstance());
        }
    }
}

All those jars contain a class that implements an interface Plugin.

+-- Main.jar
|    +-- App.class
|    +-- Plugin.class
|
+-- Plugins/
|    +-- PluginTest.jar
|         +-- plugintest
|              +-- PluginTest.class
|              +-- Two.class

That's all working fine if I write my code just in the PluginTest class. But as soon as I try to access Two from PluginTest, I'm getting a big error:

Exception in thread "Thread-4" java.lang.NoClassDefFoundError: plugintest/Two
[...]

How should I load the the class correctly? Need help! Thanks.

Upvotes: 0

Views: 244

Answers (1)

talex
talex

Reputation: 20542

Do not close your classloader.

Remove cl.close();statement.

Upvotes: 1

Related Questions