我尝试在 servlet 中实现插件系统。我编写了一个类来加载插件,该插件使用 URLClassLoader 加载 jar 文件并使用 Class.forname 加载该类。
这是我的代码:
这部分创建 url 类 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);
}
这个初始化url:
private void nameToURL(String[] pluginName) throws PluginLoaderException{
try{
for(int i=0;i<pluginName.length;i++){
urls[i] = context.getResource(pluginName[i]);
}
}
最后这个创建了对象:
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());
}
}
我已经成功创建了该对象,因为我可以操作它并检索它实现的接口(interface),但我无法在 ITest 中将其强制转换以在应用程序中操作它。我有一个 ClassCastException tplugin.toto.Toto 无法转换为 fr.test.inter.ITest 。
这很奇怪,因为 Toto 实现了 ITest。
有人有想法吗?
谢谢
最佳答案
您已经创建了一个类加载器问题 - 当您使用 instanceof ITest
进行测试时,您正在使用由默认类加载器加载的 ITest
副本,但您正在测试由 URLClassloader
加载的实例。该类加载器已加载其自己的 ITest
副本,就 JVM 而言,这是一种完全不同的类型。
关于java - Servlet 中的 ClasscastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10225739/