I have the following file structure:
Y:\tmp\test
| main.groovy
|
\---impl
FooImpl.groovy
This is impl/FooImpl.groovy
:
package impl
class FooImpl {
def foo() {
"hello?!"
}
}
And main.groovy
is as simple as that:
println new impl.FooImpl().foo()
When I'm executing main.groovy
from within the Y:\tmp\test
dir everything works as expected:
Y:\tmp\test>groovy main.groovy
hello?!
However, when running it from a different directory (e.g. one level above), it will not find FooImpl
because it's not on the classpath:
Y:\tmp>groovy test\main.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Y:\tmp\test\main.groovy: 2: unable to resolve class impl.FooImpl
@ line 2, column 9.
println new impl.FooImpl().foo()
^
1 error
I'm aware this can be fixed by supplying a proper classpath:
Y:\tmp>groovy -cp test\ test\main.groovy
hello?!
However, the process calling my main.groovy script is not under my control, so I can not change the classpath unfortunately :-(
I was hoping to be able to set the classpath dynamically as described here, so I modified main.groovy
to:
this.class.classLoader.rootLoader.addURL( new URL("file:///y:/tmp/test/") )
println new impl.FooImpl().foo()
But it still doesn't work, results in the same error:
Y:\tmp>groovy test\main.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Y:\tmp\test\main.groovy: 4: unable to resolve class impl.FooImpl
@ line 4, column 9.
println new impl.FooImpl().foo()
^
1 error
Any ideas what I'm doing wrong here?
Got it thanks to this answer on stackoverflow:
https://stackoverflow.com/questions/306139/how-do-i-include-jars-in-a-groovy-script#comment11198154_306168
The issue is that imports are resolved prior to the script running. So if we delay the instantiation e.g. via reflection it will work:
w00t!