Reputation: 201
I am developing an Eclipse plugin that runs the current active file. I am using this method
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)
{
}
}
But it works when I "Launch Eclipse application" [run the plugin in another Eclipse window] but when I installed the plugin in Eclipse it doesn't work anymore. The problem is in this line
Class thisClass = classLoader.loadClass("NewFile"); It cannot find the class to be executed
Upvotes: 2
Views: 26
Reputation: 2695
I would assume that the context classloader is different when running as a plugin. Look at the classloader hierarchy obtained in your line:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
See if it differs in the two runtime contexts. If you can step-debug the plugin, you should be able to explore around the available objects and find a classloader among them that works for your dynamic class.
If you want to use a URLClassLoader
(which appears to have been abandoned in your code), you need to give it a parent, like:
new URLClassLoader(urls, this.getClass().getClassLoader())
Upvotes: 0