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.
Do not close your classloader.
Remove cl.close();
statement.