2012-04-19 24 views
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&ltpluginName.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。

有沒有人有想法?

感謝

回答

3

你已經創建了一個classoader問題 - 當你與instanceof ITest測試,您使用的是由默認的類加載器加載ITest的副本,但您正在測試由URLClassloader加載一個實例。該類加載器已加載自己的副本ITest,就JVM而言,它是完全不同的類型。

+0

我理解你的解釋,但爲什麼當我在java標準應用程序中嘗試這段代碼時,它正在工作? – scarankle 2012-04-19 10:31:14

+0

在一個標準的Java應用程序中,默認的類加載器是完全不同的,所以我認爲它的工作原因是因爲這兩個CLS之間有一個幸運的交互作用 - 或者由於在servlet容器的情況下不合適而不工作:)你不是傳遞一個明確的父類加載器到'URLClassloader'。在這種情況下,父母是什麼? – 2012-04-19 10:36:57

+0

感謝你的解釋是非常有幫助的,就像你說的在URLClassloader中傳遞默認類加載器來解決問題一樣。祝你有個愉快的日子 – scarankle 2012-04-19 10:50:11

相關問題