Class 在groovy脚本中包含类
如何在Groovy脚本中包含几个类 (这个问题与REST无关,但我使用REST将问题置于正确的上下文中) 背景: 我正在groovy中开发一个CLI,以从我们正在运行的服务中获取状态信息。状态信息作为REST接口公开 根据我在CLI上给出的参数,REST接口上会调用不同的路径。我还将实际的REST通信放在类层次结构中,以便能够重用代码,这就是我遇到的问题所在。如何在groovy脚本中简单地包含类层次结构 Groovy CLI脚本Class 在groovy脚本中包含类,class,groovy,include,Class,Groovy,Include,如何在Groovy脚本中包含几个类 (这个问题与REST无关,但我使用REST将问题置于正确的上下文中) 背景: 我正在groovy中开发一个CLI,以从我们正在运行的服务中获取状态信息。状态信息作为REST接口公开 根据我在CLI上给出的参数,REST接口上会调用不同的路径。我还将实际的REST通信放在类层次结构中,以便能够重用代码,这就是我遇到的问题所在。如何在groovy脚本中简单地包含类层次结构 Groovy CLI脚本RestCli.Groovy import restcli.Rest
RestCli.Groovy
import restcli.RestA
import restcli.RestB
if(args[0] == "A") {
new RestA().restCall()
}
else if(args[0] == "B") {
new RestB().restCall()
}
package restcli
class RestA extends RestSuper {
def restCall() {
restCall("/rest/AA")
}
}
package restcli
class RestB extends RestSuper {
def restCall() {
restCall("/rest/BB")
}
}
用于层次结构的超类restcli/RestSuper.groovy
package restcli
abstract class RestSuper {
protected def restCall(String path) {
println 'Calling: ' +path
}
abstract def restCall()
}
两个类来实现不同的调用<代码>restcli/RestA.groovy
import restcli.RestA
import restcli.RestB
if(args[0] == "A") {
new RestA().restCall()
}
else if(args[0] == "B") {
new RestB().restCall()
}
package restcli
class RestA extends RestSuper {
def restCall() {
restCall("/rest/AA")
}
}
package restcli
class RestB extends RestSuper {
def restCall() {
restCall("/rest/BB")
}
}
和restcli/RestB.groovy
import restcli.RestA
import restcli.RestB
if(args[0] == "A") {
new RestA().restCall()
}
else if(args[0] == "B") {
new RestB().restCall()
}
package restcli
class RestA extends RestSuper {
def restCall() {
restCall("/rest/AA")
}
}
package restcli
class RestB extends RestSuper {
def restCall() {
restCall("/rest/BB")
}
}
我想得到的结果很简单:
> groovy RestCli.groovy B
Calling: /rest/BB
有什么办法吗
实际上,我希望避免创建jar文件,然后使用
-classpath
选项,因为我也在使用@Grab
获取http builder,如果我使用-classpath
,那么我会遇到这样的问题:java.lang.NoClassDefFoundError:groovyx.net.http.HTTPBuilder
您可以在一个groovy脚本中放置多个类(不确定包是如何工作的)或者只需在与主脚本相同的文件夹中创建包结构作为目录结构
在您的示例中,可能是这样的:
/
+ RestCli.groovy
+ restcli/
+--+ RestSuper.groovy
+--+ RestA.groovy
+--+ RestB.groovy
> groovy RestCli.groovy B
然后可以这样调用脚本:
/
+ RestCli.groovy
+ restcli/
+--+ RestSuper.groovy
+--+ RestA.groovy
+--+ RestB.groovy
> groovy RestCli.groovy B
非常感谢。非常简单的解决方案。