I try to implement a plugin system in a servlet. I’ve written a class to load plugin that use URLClassLoader to load the jar files and Class.forname to load the class.
Here is my code:
This part create the url class Loader:
public PluginLoader(ServletContext context, String[] pluginName, String[] classToLoad) throws PluginLoaderException{
this.context = context;
urls= new URL[pluginName.length];
nameToURL(pluginName);
//create class loader
loader = new URLClassLoader(urls);
//loading the plug-in
loadPlugin(classToLoad);
}
This one initialize the url:
private void nameToURL(String[] pluginName) throws PluginLoaderException{
try{
for(int i=0;i<pluginName.length;i++){
urls[i] = context.getResource(pluginName[i]);
}
}
Finally this one create the object:
private void loadPlugin(String[] classToLoad) throws PluginLoaderException{
try{
iTest = (ITest) Class.forName(classToLoad[0],true,loader).newInstance();
}
catch(Exception e){
throw new PluginLoaderException(e.toString());
}
}
I have managed to create the object because I can manipulate it and retrieve the interface it implements but I can’t cast it in ITest to manipulate it in the application. I have a ClassCastException tplugin.toto.Toto cannot be cast to fr.test.inter.ITest .
It’s strange because Toto implements ITest.
Does anyone has an idea ?
Thanks
You’ve created a classoader issue — when you test with
instanceof ITest, you are using the copy ofITestloaded by the default classloader, but you are testing an instance loaded by theURLClassloader. That classloader has loaded its own copy ofITest, which, as far as the JVM is concerned, is a completely different type.