[英]Include classes in a groovy script
How can I include a few classes in a Groovy script? 如何在Groovy脚本中包含几个类?
(This question has nothing to do with REST, but I use REST to put the question in the right context) (此问题与REST无关,但我使用REST将问题放在正确的上下文中)
Background: I am developing a CLI in groovy to get status information from a service we are running. 背景:我正在用Groovy开发CLI,以从我们正在运行的服务中获取状态信息。 The status information is exposed as a REST interface. 状态信息作为REST接口公开。
Depending on the argument I give on the CLI, different paths are called on the REST interface. 根据我在CLI上给出的参数,在REST接口上调用不同的路径。 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. 我还将实际的REST通信放入了类层次结构中,以便能够重用代码,这就是我遇到的问题。 How can I include the class hierarchy in my groovy script in an easy way? 如何以简单的方式将类层次结构包含在groovy脚本中?
Groovy CLI-script RestCli.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()
}
Super class for the hierarcy restcli/RestSuper.groovy
用于层级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
和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
我实际上想避免创建一个jar文件,然后使用-classpath
选项,因为我也使用@Grab
来获取http-builder,如果我使用-classpath
那么我会遇到这样的问题: java.lang.NoClassDefFoundError: groovyx.net.http.HTTPBuilder
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.