Search code examples
javagroovyclasspathclassloader

Does a Groovy script run from Java have the same classpath?


I'm trying to run a Groovy script from Java using GroovyClassLoader. Basically, what I do is this:

GroovyClassLoader groovyLoader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader());
clazz = groovyLoader.parseClass(myFile);
GroovyObject go = (GroovyObject) go.newInstance();
return go.invokeMethod("MyMethod", myObject);

The problem is that when I'm parsing the groovy file, my imports are not resolved even though the classes are in the Java classpath. If I add a line with:

groovyLoader.addClasspath("MyclassPath");

then everything works fine (this is our last resort in case we are unable to figure this out). This makes me think that there are two differents classpaths, one for Java and one for Groovy. But still, since I'm passing the Java classloader as a constructor argument for the GroovyClassloader, I'd think that if the classes are not found on the Groovy classpath, they should be looked up in Java's.

Am I wrong? Can someone shed some light on this?

Thank you.


Solution

  • After lots of tests, I've figured out that the Groovy launched by Java has indeed the same classpath of the launching Java. The problem on the OP was caused by a configuration problem on our side.

    For future readers, I recommend this question How to get classpath in Groovy? which gave a lot of help during the debugging process.