Skip to content

Instantly share code, notes, and snippets.

@tknerr
Last active March 30, 2024 06:56
Show Gist options
  • Select an option

  • Save tknerr/42258e761f2a0f95a92b to your computer and use it in GitHub Desktop.

Select an option

Save tknerr/42258e761f2a0f95a92b to your computer and use it in GitHub Desktop.
groovy script classpath problem

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?

@juliantcook
Copy link

@agray - works for me if I call addUrl() on classLoader.this.class.classLoader.addUrl(url)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment