Include classes in a groovy script
You can put multiple classes in one groovy script (not sure how/if packages work that way) or just create the package structure as a directory structure in the same folder as your main script.
In your example that could look like this:
/
+ RestCli.groovy
+ restcli/
+--+ RestSuper.groovy
+--+ RestA.groovy
+--+ RestB.groovy
You could then call your script like this:
> groovy RestCli.groovy B
Comments
-
lagurz almost 2 years
How can I include a few classes in a Groovy script?
(This question has nothing to do with REST, but I use REST to put the question in the right context)
Background: I am developing a CLI in groovy to get status information from a service we are running. The status information is exposed as a REST interface.
Depending on the argument I give on the CLI, different paths are called on the REST interface. I have also put the actual REST communication in a class hierarchy to be able to reuse the code and this is where I have the problem. How can I include the class hierarchy in my groovy script in an easy way?
Groovy CLI-script
RestCli.groovy
import restcli.RestA import restcli.RestB if(args[0] == "A") { new RestA().restCall() } else if(args[0] == "B") { new RestB().restCall() }
Super class for the hierarcy
restcli/RestSuper.groovy
package restcli abstract class RestSuper { protected def restCall(String path) { println 'Calling: ' +path } abstract def restCall() }
Two classes to implement different calls.
restcli/RestA.groovy
package restcli class RestA extends RestSuper { def restCall() { restCall("/rest/AA") } }
and
restcli/RestB.groovy
package restcli class RestB extends RestSuper { def restCall() { restCall("/rest/BB") } }
The result I want to get is simply:
> groovy RestCli.groovy B Calling: /rest/BB
Any ideas on how to do this?
I would actually like to avoid creating a jar file and then use the
-classpath
option, because I'm also using@Grab
to get http-builder and if I use-classpath
then I'm getting problems like this one:java.lang.NoClassDefFoundError: groovyx.net.http.HTTPBuilder
-
lagurz about 11 yearsThank you! Very simple solution.