小编lag*_*urz的帖子

在groovy脚本中包含类

如何在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)

我想得到的结果很简单:

> …
Run Code Online (Sandbox Code Playgroud)

groovy class include

2
推荐指数
1
解决办法
1万
查看次数

标签 统计

class ×1

groovy ×1

include ×1