2

我正在开发一个运行当前活动文件的 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 中安装插件时它不再工作了。问题出在这一行

类 thisClass = classLoader.loadClass("NewFile"); 它找不到要执行的类

4

1 回答 1

0

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

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

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

如果您想使用 a URLClassLoader(在您的代码中似乎已被放弃),您需要给它一个父级,例如:

new URLClassLoader(urls, this.getClass().getClassLoader())
于 2013-06-23T05:29:14.990 回答