Groovy脚本中功能的“包含" [英] 'include' of functions in groovy scripts
本文介绍了Groovy脚本中功能的“包含"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用Groovy编写许多脚本.而且我需要在脚本中重复使用某种代码.我该怎么办?
I'm writing a number of scripts in groovy. And I need some kind of code reuse in my scripts. How can I do it?
- 我可以将这段代码放在一个类中.但这几乎不支持解决方案-代码的一部分在解释的脚本中,另一部分在编译的类中
- 我可以使用'evaluate',但是我需要重用具有返回值的函数.我尝试对函数定义进行评估",但似乎不起作用.
您能推荐一些在脚本中包含"函数定义的方法吗?
Can you recommend some approach of "include" of functions definitions in a script?
谢谢!
推荐答案
无需编译groovy脚本,您可以包括一个定义为类的脚本.
There is no need to compile the groovy script, you can include a script defined as a class just fine.
获取文件SomeClass.groovy
Take a file SomeClass.groovy
class SomeClass {
def add(a,b){
return a+b
}
}
和脚本SomeScript.groovy
and a script SomeScript.groovy
println(new SomeClass().add(1,1))
只要SomeClass.groovy在CLASSPATH上,此方法就可以使用.
This will work as long as SomeClass.groovy is on the CLASSPATH.
编辑
class SomeClass {
def static add(a,b){
return a+b
}
}
呼叫方式:
println(SomeClass.add(1,1))
这篇关于Groovy脚本中功能的“包含"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文