安装插件时,动态执行无效

时间:2013-06-16 20:27:37

标签: java eclipse-plugin dynamic-execution

我正在开发一个运行当前活动文件的Eclipse插件。我正在使用这种方法

public static void runIt(String fileToCompile,String packageName) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException, SecurityException, NoSuchMethodException
    {

        File file = new File(fileToCompile);

        try
        {
            // Convert File to a URL
            URL url = file.toURL(); // file:/classes/demo
            URL[] urls = new URL[] { url };

            // Create a new class loader with the directory
            ClassLoader loader = new URLClassLoader(urls);

            ClassLoader classLoader = Thread.currentThread()
                    .getContextClassLoader();

            Class<?> thisClass = classLoader.loadClass("NewFile");
            Object newClassAInstance = thisClass.newInstance();
            Class params[] = new Class[1];
            params[0]=String[].class;
            Object paramsObj[] = {};
            String m=null;
            Object instance = thisClass.newInstance();
            Method thisMethod = thisClass.getDeclaredMethod("main", params);
            String methodParameter = "a quick brown fox";
            // run the testAdd() method on the instance:
            System.out.println((String)thisMethod.invoke(instance,(Object)m));



        }
        catch (MalformedURLException e)
        {
        }

    }

但是当我“启动Eclipse应用程序”[在另一个Eclipse窗口中运行插件]时它会起作用但是当我在Eclipse中安装插件时它不再起作用了。 问题出在这一行

  

Class thisClass = classLoader.loadClass(“NewFile”);    它无法找到要执行的类

1 个答案:

答案 0 :(得分:0)

我认为当作为插件运行时,上下文类加载器是不同的。查看在您的行中获得的类加载器层次结构:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

在两个运行时上下文中查看它是否不同。如果你可以对插件进行逐步调试,你应该能够探索可用的对象并找到适合你的动态类的类加载器。

如果您想使用URLClassLoader(似乎已在代码中放弃),则需要为其提供父级,例如:

new URLClassLoader(urls, this.getClass().getClassLoader())