我正在开发一个运行当前 Activity 文件的 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"); It cannot find the class to be executed
最佳答案
我假设上下文类加载器在作为插件运行时是不同的。查看您行中获得的类加载器层次结构:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
看看它在两个运行时上下文中是否不同。如果您可以逐步调试该插件,您应该能够探索可用对象并在其中找到适用于您的动态类的类加载器。
如果您想使用 URLClassLoader
(它似乎已在您的代码中被放弃),您需要给它一个父级,例如:
new URLClassLoader(urls, this.getClass().getClassLoader())
关于java - 安装插件后动态执行不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17137405/