在groovy脚本中包含类

lag*_*urz 2 groovy class include

如何在Groovy脚本中包含几个类?

(这个问题与REST无关,但我使用REST将问题放在正确的上下文中)

背景:我在groovy中开发CLI以从我们正在运行的服务获取状态信息.状态信息作为REST接口公开.

根据我在CLI上提供的参数,在REST接口上调用不同的路径.我还将实际的REST通信放在类层次结构中,以便能够重用代码,这就是我遇到问题的地方.如何以简单的方式在我的groovy脚本中包含类层次结构?

Groovy CLI脚本 RestCli.groovy

import restcli.RestA
import restcli.RestB

if(args[0] == "A") {
    new RestA().restCall()
}
else if(args[0] == "B") {
    new RestB().restCall()
}
Run Code Online (Sandbox Code Playgroud)

层级超级 restcli/RestSuper.groovy

package restcli

abstract class RestSuper {

    protected def restCall(String path) {
        println 'Calling: ' +path
    } 

    abstract def restCall()

}
Run Code Online (Sandbox Code Playgroud)

两个类实现不同的调用. restcli/RestA.groovy

package restcli

class RestA extends RestSuper {

    def restCall() {
        restCall("/rest/AA")
    }       

}
Run Code Online (Sandbox Code Playgroud)

restcli/RestB.groovy

package restcli

class RestB extends RestSuper {

    def restCall() {
        restCall("/rest/BB")
    }

}
Run Code Online (Sandbox Code Playgroud)

我想得到的结果很简单:

> groovy RestCli.groovy B
Calling: /rest/BB
Run Code Online (Sandbox Code Playgroud)

关于如何做到这一点的任何想法?

我实际上想避免创建一个jar文件,然后使用该-classpath选项,因为我也@Grab用来获取http-builder,如果我使用-classpath那么我会遇到这样的问题:java.lang.NoClassDefFoundError: groovyx.net.http.HTTPBuilder

hsa*_*san 5

你可以把多个类在一个Groovy脚本(不知道如何/如果包工作方式),或者只是在同一文件夹作为主脚本创建的目录结构中的封装结构.

在您的示例中,可能如下所示:

/
+ RestCli.groovy
+ restcli/
+--+ RestSuper.groovy
+--+ RestA.groovy
+--+ RestB.groovy
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样调用你的脚本:

> groovy RestCli.groovy B
Run Code Online (Sandbox Code Playgroud)