2017-01-03 125 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");