Combining the information from many posts on this site and many others, I got the following code to dynamically add (at run time) a directory containing classes to the classpath and load a class within that directory.
I'm using OSGi bundles and running from eclipse an "Eclipse Application" (a kind of Run Configuration).
This is the code I'm using:
CASE 1: (both cases are different things I've tried to do the same thing.)
File file = new File("/Users/alek/fastFIX/myJPass/"); URL url = file.toURI().toURL(); URL[] urls = new URL[]{url}; ClassLoader cl = new URLClassLoader(urls); Class cls = cl.loadClass("GuiLauncher"); //the file GuiLauncher.class is in the /Users/alek/fastFIX/myJPass/ directory Class[] argTypes = new Class[] { String[].class }; Method main = cls.getDeclaredMethod("main", argTypes); //trying to run the main class main.invoke(null, (Object) args); I don't get any error, and nothing happens. I've also tryied the following, as I actually need the loaded class to interact with other (already loaded) classes.
CASE 2:
ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader(); URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { new File("/Users/alek/fastFIX/myJPass/").toURL() }, currentThreadClassLoader); Thread.currentThread().setContextClassLoader(urlClassLoader); then i load like this:
Class<?> c = Class.forName("GuiLauncher"); or like this:
Class<?> c = Thread.currentThread().getContextClassLoader().loadClass("GuiLauncher"); and try to invoke the main function like this:
Class[] argTypes = new Class[] { String[].class }; Method main = cls.getDeclaredMethod("main", argTypes); //trying to run the main class main.invoke(null, (Object) args); here also nothing happens.
Any clue of what could be happening? I've read all related posts here and many places else with no luck.
MyPlugin m = cls.newInstance(); m.runPlugin(magic, hax);where MyPlugin is an interface that your runtime class implements.GuiLauncherclass before the execution of the classloader, it would get loaded from the classpath by the default classloader. So in that case yourloadClasswill not have any effect as it will check with parent classloader to see if the class it already loaded and find that it is loaded.