2013-04-16 79 views
1

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

(这个问题有没有关系休息,但我使用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() 
} 

为hierarcy超类restcli/RestSuper.groovy

package restcli 

abstract class RestSuper { 

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

    abstract def restCall() 

} 

两个类来实现不同的呼叫。 restcli/RestA.groovy

package restcli 

class RestA extends RestSuper { 

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

} 

restcli/RestB.groovy

package restcli 

class RestB extends RestSuper { 

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

} 

我想要得到的结果很简单:

> groovy RestCli.groovy B 
Calling: /rest/BB 

如何做到这一点任何想法?

我真的想避免创建一个jar文件,然后使用-classpath选项,因为我还使用@Grab得到HTTP建设者,如果我使用-classpath然后我得到的问题,像这样:java.lang.NoClassDefFoundError: groovyx.net.http.HTTPBuilder

回答

4

您可以在一个groovy脚本中放入多个类(不知道如何/如果软件包以这种方式工作),或者只是在与主脚本相同的文件夹中创建包结构作为目录结构。

在您的例子,可能是这样的:

/ 
+ RestCli.groovy 
+ restcli/ 
+--+ RestSuper.groovy 
+--+ RestA.groovy 
+--+ RestB.groovy 

然后,您可以打电话给你的脚本是这样的:

> groovy RestCli.groovy B 
+0

谢谢!很简单的解决方案 – lagurz