Let's say I've compiled a Groovy script using Groovyc, which has generated one or more .class files in the file system. From a Java application, how do I add those classes to the classpath dynamically in order to load them and call their methods? The goal is to pre-compile Groovy scripts and store them into the database, so evaluation can be performed from compiled versions of the scripts.
+1
A:
You need to write your own classloader.
This javadoc link has an example of how you can define a custom one.
Alexander Pogrebnyak
2010-07-28 00:32:37
It works, thanks! I'm evaluating if that would be the best approach in the scope of my project.
Tiago Fernandez
2010-07-28 09:21:53
+3
A:
You can create an instance of URLClassLoader to load new classes from a directory:
URL dirUrl = new URL("file:/" + "path_to_dir" + "/"); // 1
URLClassLoader cl = new URLClassLoader(new URL[] {dirUrl},
getClass().class.getClassLoader()); // 2
Class loadedClass = cl.loadClass("com.xyz.MyClass");
MyClass obj = (MyClass) loadedClass.newInstance();
obj.doSomething();
Line 1 creates the URL
to the directory where the .class files reside.
Line 2 creates a new URLClassLoader
instance. First argument is an array of URLs to be used as the source. You can specify multiple directory URLs within the array. Second argument is the classloader that will become the parent of this new classloader. We pass the classloader of the class executing the above code as this argument.
The classes loaded by a child classloader can access the classes loaded by the parent classloader.
Samit G.
2010-07-28 02:38:44
It works, with a single modification on line 2 because in my case I'm loading a compiled Groovy script: instead of getClass().class.getClassLoader() I use new GroovyClassLoader(). Thanks.
Tiago Fernandez
2010-07-28 08:35:23