2017-01-03 128 views
0

我已經爲Java反射創建了一個Utility類。如果方法名稱作爲參數傳遞 ,那麼我的意圖是什麼,那麼它應該返回Collecton的值。該實用程序類是在Eclipse插件項目(com.abc.utility)中創建的。 我將這個工具類添加到另一個插件項目(com.abc.dao)。現在當我調用這個實用程序方法時,我得到了ClassNotFoundException。 我明白了這個問題。我不想將依賴項添加到com.abc.utility項目中。而不是 com.abc.utility插件項目應該添加爲其他項目的依賴項。classnotfound異常反射

我不知道如何解決。你能幫我解決這個問題嗎?

@SuppressWarnings({ "unchecked", "rawtypes" }) 
    public <K>Collection<K> getCollection(T t, String methodName) { 

     Method[] methods =t.getClass().getMethods();   

     for (Method method : methods) {   
      String name = method.getName(); 
      if (name.equals(methodName)) { 
       String name2 = method.getReturnType().getName(); 
       Object newInstance = null; 
       try { 
        newInstance = Class.forName(name2).newInstance(); 
       } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e1) { 
        e1.printStackTrace(); 
       } 
       if (newInstance instanceof Collection) { 
        try { 
         return (Collection)method.invoke(t, null); 
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { 
         e.printStackTrace(); 
        } 
       } 

      } 
     } 

     return Collections.emptyList(); 
    } 

回答

0

你不能這樣做。每個Eclipse插件都有一個單獨的類路徑,因此插件com.abc.utilityClass.forName只適用於插件或其依賴項中的類。其他類不會在插件的類路徑中,並且將無法找到它們。

您可以在其他插件中加載類,但前提是您知道包含該類的插件。要做到這一點,你使用:

Bundle bundle = ... bundle for the plugin containing the class 

Class<?> theClass = bundle.loadClass("class name"); 

您可以使用您可以通過插件的id Bundle

Bundle bundle = Platform.getBundle("plugin id");