How to use multiple classes in multiple files in scripts?

3.3k views Asked by At

I need to make a standalone Groovy script that does not require compilation and runs without Groovy installed. It works well, but it fails to recognize any other script than the main script.

My folder structure is the following:

libs\
    groovy-all-2.4.3.jar
    ivy-2.4.0.jar
src\
    makeRelease.groovy
    ReleaseHelper.groovy

I am launching the script this way from the src folder:

java -cp "../libs/*" makeRelease.groovy

makeRelease looks like this:

public class makeRelease {
    public static void main(String... args) {
         new ReleaseHelper()
         ...
    }
}

When run this is the output:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
src\makeRelease.groovy: 5: unable to resolve class ReleaseHelper

How can I include other classes (that reside in separate files) in such portable scripts?

1

There are 1 answers

2
jalopaba On BEST ANSWER

I think that it is easier than you think:

libs\
    groovy-all-2.4.3.jar
src\
    main.groovy
    Greeter.groovy

Where main.groovy

public class Main {
    public static void main(args) {
        println 'Main script starting...'
        def greeter = new Greeter()
        greeter.sayHello()
    }
}

and Greeter.groovy

class Greeter {
    def sayHello() {
        println 'Hello!'
    }
}

Simply add to the classpath the folders where you have the classes in separate files:

java -cp .;..\libs\groovy-all-2.4.3.jar groovy.ui.GroovyMain main.groovy

The above yields:

Main script starting...
Hello!