Re: Running groovy programs

Jochen Theodorou <[email protected]>
Newsgroups gmane.comp.lang.groovy.user
Message-ID <[email protected]>
On 18.03.22 15:32, Andriy Rysin wrote:
> This approach may work well for simple file include but if I have
> packages (and import statements, which is inevitable if program grows)
> it does not compile.

Let me explain my suggestion in more detail.

you want to start a script Loader.groovy with groovy
/path/to/scripts/Loader.groovy <myfile>

The loader could look something like this:

> import java.nio.file.Path
>
> @groovy.transform.SourceURI def sourceURI
> assert sourceURI instanceof java.net.URI
> def url =  Path.of(sourceURI.path).parent.toUri().toURL()
> def gcl = new GroovyClassLoader(this.class.classLoader)
> gcl.addURL(url)
> def c = gcl.loadClass("TagText")
> c.main(this.args)

Here I load the class TagText written in Groovy, no precompiled. Using
sourceURI I found the directory where Loader.groovy resides in as url.
Then I spawn a new class loader which knows this directory and let it
load my actual main class TagText. For this to work TagText has to be in
the same director as Loader. Should TagText be in a package, you have to
use the package name as well of course. For example foo/TagText.groovy
should have the package foo and then I would have to do
loadClass("foo.TagText") to load it.

This way I can load TagText from anywhere using Loader, as TagText is in
a known relative position to Loader.

TagText can then of course have further dependencies. You can also add
jars this way (you have to produce an url with jar protocol then I think)

BTW: this.args passes through the arguments. This way <myfile> is passed
to TagText.

bye Jochen
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.