0
我嘗試在servlet中實現插件系統。我寫了一個類來加載使用URLClassLoader加載jar文件和Class.forname加載類的插件。
這裏是我的代碼:
這部分創建URL類裝載器:
Servlet中的ClasscastException
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);
}
這一個初始化的網址:
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());
}
}
我已經設法創建對象,因爲我可以n操作它並檢索它實現的接口,但是我不能在ITest中將它投射到應用程序中進行操作。我有一個ClassCastException tplugin.toto.Toto不能轉換爲fr.test.inter.ITest。
很奇怪,因爲Toto實現了ITest。
有沒有人有想法?
感謝
我理解你的解釋,但爲什麼當我在java標準應用程序中嘗試這段代碼時,它正在工作? – scarankle 2012-04-19 10:31:14
在一個標準的Java應用程序中,默認的類加載器是完全不同的,所以我認爲它的工作原因是因爲這兩個CLS之間有一個幸運的交互作用 - 或者由於在servlet容器的情況下不合適而不工作:)你不是傳遞一個明確的父類加載器到'URLClassloader'。在這種情況下,父母是什麼? – 2012-04-19 10:36:57
感謝你的解釋是非常有幫助的,就像你說的在URLClassloader中傳遞默認類加載器來解決問題一樣。祝你有個愉快的日子 – scarankle 2012-04-19 10:50:11