2012-04-03 62 views
1

我想要一個模塊化應用程序,它在運行時註冊JAR模塊。爲此,我使用Netbeans Lookup API。運行時註冊JAR

問題是,我無法直接在庫文件夾中複製某些JAR文件,因爲運行實例無法識別它。 在模塊中,我配置了META-INF.services以及接口的包名稱和模塊包名稱。

這裏是我的代碼示例:

while(true){ 
    Lookup lkp; 
    Collection<TestInterface> tests = null; 
    Template tmpl; 
    final Lookup.Result rslt; 

    lkp= Lookup.getDefault(); 
    //lkp=Lookups.forPath("modules-path"); 
    tmpl= new Template(TestInterface.class); 
    rslt= lkp.lookup(testTemplate); 
    tests = rslt.allItems(); 

    Lookup.getDefault().lookup(TestInterface.class); 
     rslt.addLookupListener(new LookupListener() { 
      @Override 
      public void resultChanged(LookupEvent le) { 
       reaction(rslt); 
      } 
     }); 

     reaction(rslt); 
    } 
} 

private static void reaction(Lookup.Result r) { 
    for (Iterator i = r.allInstances().iterator(); i.hasNext();) { 
     TestInterface s = (TestInterface) i.next(); 
     System.out.println(s.somemethod()); 
    } 
} 

任何建議/提示怎麼解決呢?

回答

1

您可以使用OSGi來代替Netbeans查找。很明顯,你可以控制你需要加載的jar文件,所以它應該可以正常工作。

你需要改變你的jar配置才能得到一個OSGi包。爲此,您必須更改MANIFEST.MF文件,如下所述:

http://www.vogella.de/articles/OSGi/article.html#osgiarch_manifest http://www.javaworld.com/javaworld/jw-03-2008/jw-03-osgi1.html?頁= 2

然後,您可以激活使用您在清單中定義的BundleActivator的jar文件,就像在這裏解釋:

http://www.vogella.de/articles/OSGi/article.html#codebundle

然後,你可以發佈你的包作爲服務和消費它在您的應用程序中:

http://www.eclipsezone.com/eclipse/forums/t90796.html

+0

我知道OSGi,我會考慮如果lookup-api會成爲瓶頸。你知道在OSGi中是否可以在不聲明庫的情況下「插入」模塊。例如,我只是在主模塊運行時將該jar放在文件夾中,然後主模塊識別它並使用來自模塊插入模塊的方法? – xplorer00 2012-04-03 15:04:53

+0

我不是我自己的OSGi專家,我不想誤導你,但我不認爲這是可能的。據我所知,一個jar文件需要在其MANIFEST.MF文件中包含OSGi參數以便被OSGi識別。但一個更有經驗的建議將是有益的... – 2012-04-03 17:42:16

+0

好的,謝謝你的提示和編輯:) – xplorer00 2012-04-04 07:36:18